deepwork-node-watchdog 1.0.0 → 1.0.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
@@ -24,18 +24,45 @@ npm install deepwork-node-watchdog
24
24
 
25
25
  ## Uso como CLI
26
26
 
27
- ### Iniciar el watchdog
27
+ ### Iniciar el watchdog con un archivo de lista negra
28
28
 
29
29
  ```bash
30
30
  deepwork-watchdog --blacklist /ruta/absoluta/a/blacklist.txt
31
31
  ```
32
32
 
33
+ ### Iniciar el watchdog con una lista de procesos separados por coma
34
+
35
+ ```bash
36
+ deepwork-watchdog --blacklist discord,whatsapp,spotify
37
+ ```
38
+
39
+ ### Especificar intervalo de escaneo
40
+
41
+ ```bash
42
+ deepwork-watchdog --blacklist discord,spotify --interval 5000
43
+ ```
44
+
33
45
  ### Listar procesos en ejecución
34
46
 
35
47
  ```bash
36
48
  deepwork-watchdog --list
37
49
  ```
38
50
 
51
+ ### Ver la versión
52
+
53
+ ```bash
54
+ deepwork-watchdog --version
55
+ ```
56
+
57
+ ### Argumentos disponibles
58
+
59
+ | Argumento | Tipo | Default | Descripción |
60
+ |----------------|-----------|---------|-----------------------------------------------------------------------------|
61
+ | `--blacklist` | `string` | — | Ruta absoluta a un archivo de lista negra, o nombres separados por coma |
62
+ | `--interval` | `number` | `3000` | Intervalo entre escaneos en milisegundos |
63
+ | `--list` | `boolean` | — | Lista los procesos activos del sistema y termina |
64
+ | `--version` | `boolean` | — | Muestra la versión del paquete y termina |
65
+
39
66
  ### Archivo de lista negra (`blacklist.txt`)
40
67
 
41
68
  Cada línea es el nombre de un proceso a matar. Las líneas vacías y los comentarios (`#`) son ignorados. La extensión `.exe` es opcional.
@@ -52,13 +79,12 @@ spotify
52
79
  ## Uso como librería
53
80
 
54
81
  ```ts
55
- import { start, stop, isRunning, listProcesses } from 'deepwork-node-watchdog';
82
+ import { start, stop, scan, isRunning, listProcesses } from 'deepwork-node-watchdog';
56
83
 
57
84
  // Iniciar el watchdog con una lista de procesos
58
85
  start({
59
86
  blacklist: ['discord', 'whatsapp', 'spotify'],
60
- intervalMs: 5000, // Intervalo de escaneo en ms (default: 3000)
61
- logFile: 'watchdog.log', // Opcional: archivo de log
87
+ intervalMs: 5000, // Intervalo de escaneo en ms (default: 3000)
62
88
  });
63
89
 
64
90
  // Detener el watchdog
@@ -67,41 +93,38 @@ stop();
67
93
  // Verificar si está corriendo
68
94
  console.log(isRunning()); // true | false
69
95
 
96
+ // Escaneo único (sin loop)
97
+ await scan(['discord', 'spotify']);
98
+
99
+ // También acepta ruta a archivo de lista negra
100
+ await scan('/ruta/absoluta/a/blacklist.txt');
101
+
70
102
  // Listar procesos activos
71
103
  const processes = await listProcesses();
72
104
  processes.forEach(p => console.log(`${p.name} (PID: ${p.pid})`));
73
105
  ```
74
106
 
75
- ### También puedes usar un archivo de lista negra
76
-
77
- ```ts
78
- start({
79
- blacklistPath: '/ruta/absoluta/a/blacklist.txt',
80
- intervalMs: 3000,
81
- });
82
- ```
83
-
84
107
  ---
85
108
 
86
109
  ## API
87
110
 
88
111
  ### `start(options: WatchdogOptions): void`
89
112
 
90
- Inicia el watchdog. Si ya está corriendo, no hace nada.
113
+ Inicia el watchdog en loop. Si ya está corriendo, no hace nada.
91
114
 
92
- | Opción | Tipo | Default | Descripción |
93
- |-----------------|------------|------------------|--------------------------------------------------|
94
- | `blacklist` | `string[]` | — | Lista de nombres de procesos a matar |
95
- | `blacklistPath` | `string` | | Ruta absoluta a un archivo de lista negra |
96
- | `intervalMs` | `number` | `3000` | Intervalo entre escaneos en milisegundos |
97
- | `logFile` | `string` | — | Ruta al archivo de log (opcional) |
98
-
99
- > Se debe especificar `blacklist` o `blacklistPath`. Si no se especifica ninguno, el watchdog se inicia pero no hace nada.
115
+ | Opción | Tipo | Default | Descripción |
116
+ |--------------|-----------------------|---------|-------------------------------------------------------------------|
117
+ | `blacklist` | `string \| string[]` | — | Ruta a un archivo de lista negra, o array de nombres de procesos |
118
+ | `intervalMs` | `number` | `3000` | Intervalo entre escaneos en milisegundos |
100
119
 
101
120
  ### `stop(): void`
102
121
 
103
122
  Detiene el watchdog y limpia el timer interno.
104
123
 
124
+ ### `scan(blacklist: string | string[]): Promise<void>`
125
+
126
+ Ejecuta un escaneo único. Acepta un array de nombres de procesos o la ruta absoluta a un archivo de lista negra.
127
+
105
128
  ### `isRunning(): boolean`
106
129
 
107
130
  Retorna `true` si el watchdog está activo.
@@ -112,20 +135,6 @@ Retorna la lista de procesos activos en el sistema.
112
135
 
113
136
  ---
114
137
 
115
- ## Configuración CLI (`watchdog.conf`)
116
-
117
- Cuando se usa como CLI, el watchdog lee un archivo `watchdog.conf` en el directorio de instalación:
118
-
119
- ```ini
120
- # Intervalo entre escaneos (milisegundos)
121
- INTERVAL_MS=3000
122
-
123
- # Archivo de log (dejar vacío para desactivar)
124
- LOG_FILE=watchdog.log
125
- ```
126
-
127
- ---
128
-
129
138
  ## Compatibilidad
130
139
 
131
140
  | Sistema operativo | Comando para listar | Comando para matar |
@@ -137,4 +146,4 @@ LOG_FILE=watchdog.log
137
146
 
138
147
  ## Licencia
139
148
 
140
- ISC — Kevin Javier Reyes
149
+ ISC — Kevin Javier Reyes
@@ -35,7 +35,6 @@ var __importStar = (this && this.__importStar) || (function () {
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
36
  exports.loadBlacklist = loadBlacklist;
37
37
  const fs = __importStar(require("fs"));
38
- const normalize_util_1 = require("../utils/normalize.util");
39
38
  /**
40
39
  * Read the content file at the given path.
41
40
  *
@@ -55,8 +54,7 @@ function loadBlacklist(filePath) {
55
54
  .readFileSync(filePath, "utf8")
56
55
  .split("\n")
57
56
  .map((l) => l.trim())
58
- .filter((l) => l && !l.startsWith("#"))
59
- .map(normalize_util_1.normalizeProcessName);
57
+ .filter((l) => l && !l.startsWith("#"));
60
58
  }
61
59
  catch {
62
60
  return [];
@@ -1,4 +1,4 @@
1
- export declare function killProcess(pid: number, name: string, logFile?: string): Promise<void>;
1
+ export declare function killProcess(pid: number, name: string): Promise<void>;
2
2
  export declare function listProcesses(): Promise<{
3
3
  pid: number;
4
4
  name: string;
@@ -41,7 +41,7 @@ const os = __importStar(require("os"));
41
41
  const log_util_1 = require("../utils/log.util");
42
42
  const normalize_util_1 = require("../utils/normalize.util");
43
43
  const execAsync = (0, util_1.promisify)(child_process_1.exec);
44
- async function killProcess(pid, name, logFile) {
44
+ async function killProcess(pid, name) {
45
45
  try {
46
46
  if (os.platform() === "win32") {
47
47
  await execAsync(`taskkill /F /PID ${pid}`, { timeout: 5000 });
@@ -49,10 +49,10 @@ async function killProcess(pid, name, logFile) {
49
49
  else {
50
50
  await execAsync(`kill -9 ${pid}`, { timeout: 5000 });
51
51
  }
52
- (0, log_util_1.log)(`Killed process: ${name} (PID: ${pid})`, logFile);
52
+ (0, log_util_1.log)(`Killed process: ${name} (PID: ${pid})`);
53
53
  }
54
54
  catch (err) {
55
- (0, log_util_1.log)(`Failed to kill ${name} (PID: ${pid}): ${err}`, logFile);
55
+ (0, log_util_1.log)(`Failed to kill ${name} (PID: ${pid}): ${err}`);
56
56
  }
57
57
  }
58
58
  async function listProcesses() {
package/dist/index.d.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import { WatchdogOptions } from "./watchdog.types";
2
+ export declare function scan(blacklist: string[] | string): Promise<void>;
2
3
  export declare function start(options: WatchdogOptions): void;
3
4
  export declare function stop(): void;
4
5
  export declare function isRunning(): boolean;
package/dist/index.js CHANGED
@@ -4,6 +4,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.listProcesses = void 0;
7
+ exports.scan = scan;
7
8
  exports.start = start;
8
9
  exports.stop = stop;
9
10
  exports.isRunning = isRunning;
@@ -15,25 +16,20 @@ let activeOptions = null;
15
16
  async function loop() {
16
17
  if (!running || !activeOptions)
17
18
  return;
18
- const { blacklistPath, blacklist, intervalMs = 3000, logFile, } = activeOptions;
19
- await watchdog_1.default.scan(blacklistPath ?? blacklist, {
20
- INTERVAL_MS: intervalMs,
21
- LOG_FILE: logFile,
22
- });
19
+ const { blacklist, intervalMs = 3000 } = activeOptions;
20
+ await watchdog_1.default.scan(blacklist);
23
21
  if (running) {
24
22
  timer = setTimeout(loop, intervalMs);
25
23
  }
26
24
  }
25
+ async function scan(blacklist) {
26
+ return watchdog_1.default.scan(blacklist);
27
+ }
27
28
  function start(options) {
28
29
  if (running)
29
30
  return;
30
31
  running = true;
31
32
  activeOptions = options;
32
- if (!options.blacklistPath &&
33
- (!options.blacklist || options.blacklist.length === 0)) {
34
- (0, log_util_1.log)("No blacklist specified. Use options.blacklistPath or options.blacklist to set it.", options.logFile);
35
- return;
36
- }
37
33
  loop();
38
34
  }
39
35
  function stop() {
@@ -0,0 +1,14 @@
1
+ type ArgType = "string" | "boolean" | "number";
2
+ interface ArgDef {
3
+ flag: string;
4
+ type: ArgType;
5
+ required?: boolean;
6
+ description?: string;
7
+ default?: string | boolean | number;
8
+ }
9
+ type InferType<T extends ArgType> = T extends "string" ? string : T extends "boolean" ? boolean : number;
10
+ type ParsedArgs<T extends ArgDef[]> = {
11
+ [K in T[number] as K["flag"] extends `--${infer Name}` ? Name : never]: K["required"] extends true ? InferType<K["type"]> : InferType<K["type"]> | null;
12
+ };
13
+ export declare function parseArgs<const T extends ArgDef[]>(defs: T): ParsedArgs<T>;
14
+ export {};
@@ -0,0 +1,31 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.parseArgs = parseArgs;
4
+ function parseArgs(defs) {
5
+ const raw = process.argv.slice(2);
6
+ const result = {};
7
+ for (const def of defs) {
8
+ const name = def.flag.replace(/^--/, "");
9
+ const idx = raw.indexOf(def.flag);
10
+ if (def.type === "boolean") {
11
+ result[name] = idx !== -1;
12
+ }
13
+ else if (idx !== -1) {
14
+ const val = raw[idx + 1];
15
+ if (val === undefined || val.startsWith("--")) {
16
+ throw new Error(`Missing value for ${def.flag}`);
17
+ }
18
+ result[name] = def.type === "number" ? Number(val) : val;
19
+ }
20
+ else if (def.default !== undefined) {
21
+ result[name] = def.default;
22
+ }
23
+ else if (def.required) {
24
+ throw new Error(`Required argument ${def.flag} is missing`);
25
+ }
26
+ else {
27
+ result[name] = null;
28
+ }
29
+ }
30
+ return result;
31
+ }
package/dist/main.js CHANGED
@@ -5,31 +5,69 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
5
5
  };
6
6
  Object.defineProperty(exports, "__esModule", { value: true });
7
7
  const log_util_1 = require("./utils/log.util");
8
- const config_helper_1 = require("./helpers/config.helper");
8
+ const args_lib_1 = require("./libs/args.lib");
9
9
  const watchdog_1 = __importDefault(require("./watchdog"));
10
- const args = process.argv.slice(2);
11
- const blacklistIndex = args.indexOf("--blacklist");
12
- const listIndex = args.indexOf("--list");
13
- const BLACKLIST_FILE = blacklistIndex !== -1 ? args[blacklistIndex + 1] : null;
10
+ const path_1 = __importDefault(require("path"));
11
+ // Default configuration values
12
+ const DEFAULT_INTERVAL_MS = 3000;
13
+ // Define and parse command-line arguments
14
+ const args = (0, args_lib_1.parseArgs)([
15
+ {
16
+ flag: "--blacklist",
17
+ type: "string",
18
+ description: "Absolute path to blacklist file or a comma-separated list of process names",
19
+ },
20
+ {
21
+ flag: "--list",
22
+ type: "boolean",
23
+ description: "List current running processes",
24
+ },
25
+ {
26
+ flag: "--version",
27
+ type: "boolean",
28
+ description: "Show the version of the watchdog",
29
+ },
30
+ {
31
+ flag: "--interval",
32
+ type: "number",
33
+ description: "Interval in milliseconds for scanning processes",
34
+ default: DEFAULT_INTERVAL_MS,
35
+ },
36
+ ]);
14
37
  (0, log_util_1.log)("Process Watchdog started" +
15
- (BLACKLIST_FILE ? ` with blacklist file: ${BLACKLIST_FILE}` : ""));
38
+ (args.blacklist ? ` with blacklist file: ${args.blacklist}` : ""));
16
39
  let running = true;
40
+ let blacklistPathOrNames = null;
17
41
  let timer;
42
+ function validateArgsRequirementsToScan() {
43
+ if (!args.blacklist) {
44
+ (0, log_util_1.log)("No blacklist file or process names specified. Use --blacklist <absolutePath> or a comma-separated list of process names to set it.");
45
+ return false;
46
+ }
47
+ if (args.interval <= 0) {
48
+ (0, log_util_1.log)("Interval must be a positive number.");
49
+ return false;
50
+ }
51
+ return true;
52
+ }
18
53
  async function loop() {
19
54
  if (!running)
20
55
  return;
21
- const config = (0, config_helper_1.loadConfig)();
22
- if (!BLACKLIST_FILE) {
23
- (0, log_util_1.log)("No blacklist file specified. Use --blacklist <absolutePath> to set it.", config.LOG_FILE);
56
+ if (!validateArgsRequirementsToScan()) {
24
57
  return;
25
58
  }
26
59
  console.log("Scanning processes...");
27
- await watchdog_1.default.scan(BLACKLIST_FILE, config);
60
+ await watchdog_1.default.scan(blacklistPathOrNames);
28
61
  if (running) {
29
- timer = setTimeout(loop, config.INTERVAL_MS);
62
+ timer = setTimeout(loop, args.interval);
30
63
  }
31
64
  }
32
- if (listIndex !== -1) {
65
+ if (args.version) {
66
+ let pkg = require(path_1.default.resolve(__dirname, "../package.json"));
67
+ console.log(`Process Watchdog version: ${pkg.version}`);
68
+ process.exit(0);
69
+ }
70
+ else if (args.list) {
33
71
  (async () => {
34
72
  const processes = await watchdog_1.default.listProcesses();
35
73
  console.log("Current running processes:");
@@ -38,6 +76,19 @@ if (listIndex !== -1) {
38
76
  })();
39
77
  }
40
78
  else {
79
+ const blacklist = args.blacklist?.trim();
80
+ if (!blacklist) {
81
+ (0, log_util_1.log)("No blacklist file or process names specified. Use --blacklist <absolutePath> or a comma-separated list of process names to set it.");
82
+ process.exit(1);
83
+ }
84
+ blacklistPathOrNames = args.blacklist.includes(",")
85
+ ? args.blacklist.split(",").map((s) => s.trim())
86
+ : path_1.default.isAbsolute(args.blacklist || "")
87
+ ? args.blacklist
88
+ : path_1.default.resolve(process.cwd(), args.blacklist || "");
89
+ console.log(`Using blacklist file or names: ${blacklistPathOrNames}`);
90
+ console.log(`Starting process scan loop with interval: ${args.interval}ms`);
91
+ console.log("Press Ctrl+C to stop the watchdog.");
41
92
  loop();
42
93
  }
43
94
  process.on("SIGINT", () => {
@@ -1 +1 @@
1
- export declare function log(message: string, logFile?: string): void;
1
+ export declare function log(message: string): void;
@@ -1,50 +1,8 @@
1
1
  "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
- Object.defineProperty(o, "default", { enumerable: true, value: v });
15
- }) : function(o, v) {
16
- o["default"] = v;
17
- });
18
- var __importStar = (this && this.__importStar) || (function () {
19
- var ownKeys = function(o) {
20
- ownKeys = Object.getOwnPropertyNames || function (o) {
21
- var ar = [];
22
- for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
- return ar;
24
- };
25
- return ownKeys(o);
26
- };
27
- return function (mod) {
28
- if (mod && mod.__esModule) return mod;
29
- var result = {};
30
- if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
- __setModuleDefault(result, mod);
32
- return result;
33
- };
34
- })();
35
2
  Object.defineProperty(exports, "__esModule", { value: true });
36
3
  exports.log = log;
37
- const fs = __importStar(require("fs"));
38
- function log(message, logFile) {
4
+ function log(message) {
39
5
  const timestamp = new Date().toISOString();
40
6
  const msg = `[${timestamp}] ${message}`;
41
7
  console.log(msg);
42
- if (logFile) {
43
- try {
44
- fs.appendFileSync(logFile, msg + "\n");
45
- }
46
- catch {
47
- /* ignore */
48
- }
49
- }
50
8
  }
@@ -1,6 +1,5 @@
1
- import { Config } from "./watchdog.types";
2
1
  import { listProcesses } from "./helpers/command.helper";
3
- declare function scan(blacklistPathOrList: string | string[], config: Config): Promise<void>;
2
+ declare function scan(blacklistPathOrList: string | string[]): Promise<void>;
4
3
  declare const _default: {
5
4
  scan: typeof scan;
6
5
  listProcesses: typeof listProcesses;
package/dist/watchdog.js CHANGED
@@ -3,8 +3,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  const blacklist_helper_1 = require("./helpers/blacklist.helper");
4
4
  const command_helper_1 = require("./helpers/command.helper");
5
5
  const normalize_util_1 = require("./utils/normalize.util");
6
- async function scan(blacklistPathOrList, config) {
7
- const { LOG_FILE } = config;
6
+ async function scan(blacklistPathOrList) {
8
7
  // Load blacklist
9
8
  const blacklist = typeof blacklistPathOrList === "string"
10
9
  ? (0, blacklist_helper_1.loadBlacklist)(blacklistPathOrList)
@@ -17,8 +16,9 @@ async function scan(blacklistPathOrList, config) {
17
16
  for (const proc of processes) {
18
17
  const normalizedName = (0, normalize_util_1.normalizeProcessName)(proc.name);
19
18
  for (const black of blacklist) {
20
- if (normalizedName.indexOf(black) !== -1) {
21
- await (0, command_helper_1.killProcess)(proc.pid, proc.name, LOG_FILE);
19
+ const normalizedBlack = (0, normalize_util_1.normalizeProcessName)(black);
20
+ if (normalizedName.indexOf(normalizedBlack) !== -1) {
21
+ await (0, command_helper_1.killProcess)(proc.pid, proc.name);
22
22
  }
23
23
  }
24
24
  }
@@ -1,17 +1,4 @@
1
- export interface Config {
2
- INTERVAL_MS: number;
3
- LOG_FILE: string;
4
- }
5
- export interface Profile {
6
- name: string;
7
- path: string;
8
- blacklistPath: string;
9
- hasBlacklist: boolean;
10
- processCount: number;
11
- }
12
1
  export interface WatchdogOptions {
13
- blacklistPath?: string;
14
- blacklist?: string[];
2
+ blacklist: string[] | string;
15
3
  intervalMs?: number;
16
- logFile?: string;
17
4
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "deepwork-node-watchdog",
3
- "version": "1.0.0",
3
+ "version": "1.0.2",
4
4
  "description": "A Node.js watchdog for DeepWork.",
5
5
  "license": "ISC",
6
6
  "author": "Kevin Javier Reyes",
@@ -13,9 +13,12 @@
13
13
  "deepwork-watchdog": "dist/main.js"
14
14
  },
15
15
  "scripts": {
16
- "start": "ts-node main.ts --blacklist blacklist.txt",
17
- "dev": "ts-node-dev --respawn --transpile-only --ignore-watch node_modules main.ts --blacklist blacklist.txt",
18
- "list": "ts-node main.ts --list",
16
+ "start": "ts-node src/main.ts --blacklist steam,epicgames,origin,ubisoft,riot,blizzard",
17
+ "list": "ts-node src/main.ts --list",
18
+ "version": "ts-node src/main.ts --version",
19
+ "start:dev": "ts-node-dev --respawn --transpile-only --ignore-watch node_modules src/main.ts --blacklist steam,epicgames,origin,ubisoft,riot,blizzard",
20
+ "list:dev": "ts-node-dev --respawn --transpile-only --ignore-watch node_modules src/main.ts --list",
21
+ "version:dev": "ts-node-dev --respawn --transpile-only --ignore-watch node_modules src/main.ts --version",
19
22
  "build": "tsc"
20
23
  },
21
24
  "devDependencies": {
@@ -23,5 +26,8 @@
23
26
  "ts-node": "^10.9.2",
24
27
  "ts-node-dev": "^2.0.0",
25
28
  "typescript": "^5.4.0"
29
+ },
30
+ "dependencies": {
31
+ "deepwork-node-watchdog": "1.0.0"
26
32
  }
27
33
  }