ecc_infisense 0.0.1

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.
@@ -0,0 +1,593 @@
1
+ /**
2
+ * Cross-platform utility functions for Claude Code hooks and scripts
3
+ * Works on Windows, macOS, and Linux
4
+ */
5
+
6
+ const fs = require('fs');
7
+ const path = require('path');
8
+ const os = require('os');
9
+ const { execSync, spawnSync } = require('child_process');
10
+
11
+ // Platform detection
12
+ const isWindows = process.platform === 'win32';
13
+ const isMacOS = process.platform === 'darwin';
14
+ const isLinux = process.platform === 'linux';
15
+
16
+ /**
17
+ * Get the user's home directory (cross-platform)
18
+ */
19
+ function getHomeDir() {
20
+ return os.homedir();
21
+ }
22
+
23
+ /**
24
+ * Get the Claude config directory
25
+ */
26
+ function getClaudeDir() {
27
+ return path.join(getHomeDir(), '.claude');
28
+ }
29
+
30
+ /**
31
+ * Get the sessions directory
32
+ */
33
+ function getSessionsDir() {
34
+ return path.join(getClaudeDir(), 'sessions');
35
+ }
36
+
37
+ /**
38
+ * Get the learned skills directory
39
+ */
40
+ function getLearnedSkillsDir() {
41
+ return path.join(getClaudeDir(), 'skills', 'learned');
42
+ }
43
+
44
+ /**
45
+ * Get the temp directory (cross-platform)
46
+ */
47
+ function getTempDir() {
48
+ return os.tmpdir();
49
+ }
50
+
51
+ /**
52
+ * Ensure a directory exists (create if not)
53
+ * @param {string} dirPath - Directory path to create
54
+ * @returns {string} The directory path
55
+ * @throws {Error} If directory cannot be created (e.g., permission denied)
56
+ */
57
+ function ensureDir(dirPath) {
58
+ try {
59
+ if (!fs.existsSync(dirPath)) {
60
+ fs.mkdirSync(dirPath, { recursive: true });
61
+ }
62
+ } catch (err) {
63
+ // EEXIST is fine (race condition with another process creating it)
64
+ if (err.code !== 'EEXIST') {
65
+ throw new Error(`Failed to create directory '${dirPath}': ${err.message}`);
66
+ }
67
+ }
68
+ return dirPath;
69
+ }
70
+
71
+ /**
72
+ * Get current date in YYYY-MM-DD format
73
+ */
74
+ function getDateString() {
75
+ const now = new Date();
76
+ const year = now.getFullYear();
77
+ const month = String(now.getMonth() + 1).padStart(2, '0');
78
+ const day = String(now.getDate()).padStart(2, '0');
79
+ return `${year}-${month}-${day}`;
80
+ }
81
+
82
+ /**
83
+ * Get current time in HH:MM format
84
+ */
85
+ function getTimeString() {
86
+ const now = new Date();
87
+ const hours = String(now.getHours()).padStart(2, '0');
88
+ const minutes = String(now.getMinutes()).padStart(2, '0');
89
+ return `${hours}:${minutes}`;
90
+ }
91
+
92
+ /**
93
+ * Get the git repository name
94
+ */
95
+ function getGitRepoName() {
96
+ const result = runCommand('git rev-parse --show-toplevel');
97
+ if (!result.success) return null;
98
+ return path.basename(result.output);
99
+ }
100
+
101
+ /**
102
+ * Get project name from git repo or current directory
103
+ */
104
+ function getProjectName() {
105
+ const repoName = getGitRepoName();
106
+ if (repoName) return repoName;
107
+ return path.basename(process.cwd()) || null;
108
+ }
109
+
110
+ /**
111
+ * Get short session ID from CLAUDE_SESSION_ID environment variable
112
+ * Returns last 8 characters, falls back to project name then 'default'
113
+ */
114
+ function getSessionIdShort(fallback = 'default') {
115
+ const sessionId = process.env.CLAUDE_SESSION_ID;
116
+ if (sessionId && sessionId.length > 0) {
117
+ return sessionId.slice(-8);
118
+ }
119
+ return getProjectName() || fallback;
120
+ }
121
+
122
+ /**
123
+ * Get current datetime in YYYY-MM-DD HH:MM:SS format
124
+ */
125
+ function getDateTimeString() {
126
+ const now = new Date();
127
+ const year = now.getFullYear();
128
+ const month = String(now.getMonth() + 1).padStart(2, '0');
129
+ const day = String(now.getDate()).padStart(2, '0');
130
+ const hours = String(now.getHours()).padStart(2, '0');
131
+ const minutes = String(now.getMinutes()).padStart(2, '0');
132
+ const seconds = String(now.getSeconds()).padStart(2, '0');
133
+ return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
134
+ }
135
+
136
+ /**
137
+ * Find files matching a pattern in a directory (cross-platform alternative to find)
138
+ * @param {string} dir - Directory to search
139
+ * @param {string} pattern - File pattern (e.g., "*.tmp", "*.md")
140
+ * @param {object} options - Options { maxAge: days, recursive: boolean }
141
+ */
142
+ function findFiles(dir, pattern, options = {}) {
143
+ if (!dir || typeof dir !== 'string') return [];
144
+ if (!pattern || typeof pattern !== 'string') return [];
145
+
146
+ const { maxAge = null, recursive = false } = options;
147
+ const results = [];
148
+
149
+ if (!fs.existsSync(dir)) {
150
+ return results;
151
+ }
152
+
153
+ // Escape all regex special characters, then convert glob wildcards.
154
+ // Order matters: escape specials first, then convert * and ? to regex equivalents.
155
+ const regexPattern = pattern
156
+ .replace(/[.+^${}()|[\]\\]/g, '\\$&')
157
+ .replace(/\*/g, '.*')
158
+ .replace(/\?/g, '.');
159
+ const regex = new RegExp(`^${regexPattern}$`);
160
+
161
+ function searchDir(currentDir) {
162
+ try {
163
+ const entries = fs.readdirSync(currentDir, { withFileTypes: true });
164
+
165
+ for (const entry of entries) {
166
+ const fullPath = path.join(currentDir, entry.name);
167
+
168
+ if (entry.isFile() && regex.test(entry.name)) {
169
+ let stats;
170
+ try {
171
+ stats = fs.statSync(fullPath);
172
+ } catch {
173
+ continue; // File deleted between readdir and stat
174
+ }
175
+
176
+ if (maxAge !== null) {
177
+ const ageInDays = (Date.now() - stats.mtimeMs) / (1000 * 60 * 60 * 24);
178
+ if (ageInDays <= maxAge) {
179
+ results.push({ path: fullPath, mtime: stats.mtimeMs });
180
+ }
181
+ } else {
182
+ results.push({ path: fullPath, mtime: stats.mtimeMs });
183
+ }
184
+ } else if (entry.isDirectory() && recursive) {
185
+ searchDir(fullPath);
186
+ }
187
+ }
188
+ } catch (_err) {
189
+ // Ignore permission errors
190
+ }
191
+ }
192
+
193
+ searchDir(dir);
194
+
195
+ // Sort by modification time (newest first)
196
+ results.sort((a, b) => b.mtime - a.mtime);
197
+
198
+ return results;
199
+ }
200
+
201
+ /**
202
+ * Read JSON from stdin (for hook input)
203
+ * @param {object} options - Options
204
+ * @param {number} options.timeoutMs - Timeout in milliseconds (default: 5000).
205
+ * Prevents hooks from hanging indefinitely if stdin never closes.
206
+ * @param {function} options.validate - Optional validation function. Receives
207
+ * parsed JSON, should return true if valid. Invalid data resolves as {}.
208
+ * @returns {Promise<object>} Parsed JSON object, or empty object if stdin is empty
209
+ */
210
+ async function readStdinJson(options = {}) {
211
+ const { timeoutMs = 5000, maxSize = 1024 * 1024, validate = null } = options;
212
+
213
+ return new Promise((resolve) => {
214
+ let data = '';
215
+ let settled = false;
216
+
217
+ function resolveWithValidation(parsed) {
218
+ if (validate && typeof validate === 'function') {
219
+ try {
220
+ if (!validate(parsed)) {
221
+ logVerbose('[hook] Input validation failed, using empty object');
222
+ resolve({});
223
+ return;
224
+ }
225
+ } catch {
226
+ logVerbose('[hook] Input validation threw, using empty object');
227
+ resolve({});
228
+ return;
229
+ }
230
+ }
231
+ resolve(parsed);
232
+ }
233
+
234
+ const timer = setTimeout(() => {
235
+ if (!settled) {
236
+ settled = true;
237
+ // Clean up stdin listeners so the event loop can exit
238
+ process.stdin.removeAllListeners('data');
239
+ process.stdin.removeAllListeners('end');
240
+ process.stdin.removeAllListeners('error');
241
+ if (process.stdin.unref) process.stdin.unref();
242
+ // Resolve with whatever we have so far rather than hanging
243
+ try {
244
+ resolveWithValidation(data.trim() ? JSON.parse(data) : {});
245
+ } catch {
246
+ resolve({});
247
+ }
248
+ }
249
+ }, timeoutMs);
250
+
251
+ process.stdin.setEncoding('utf8');
252
+ process.stdin.on('data', chunk => {
253
+ if (data.length < maxSize) {
254
+ data += chunk;
255
+ }
256
+ });
257
+
258
+ process.stdin.on('end', () => {
259
+ if (settled) return;
260
+ settled = true;
261
+ clearTimeout(timer);
262
+ try {
263
+ resolveWithValidation(data.trim() ? JSON.parse(data) : {});
264
+ } catch {
265
+ // Consistent with timeout path: resolve with empty object
266
+ // so hooks don't crash on malformed input
267
+ resolve({});
268
+ }
269
+ });
270
+
271
+ process.stdin.on('error', () => {
272
+ if (settled) return;
273
+ settled = true;
274
+ clearTimeout(timer);
275
+ // Resolve with empty object so hooks don't crash on stdin errors
276
+ resolve({});
277
+ });
278
+ });
279
+ }
280
+
281
+ /**
282
+ * Log to stderr (visible to user in Claude Code)
283
+ */
284
+ function log(message) {
285
+ console.error(message);
286
+ }
287
+
288
+ /**
289
+ * Log a verbose/debug message to stderr.
290
+ * Only prints when CLAUDE_HOOK_VERBOSE=1 is set.
291
+ */
292
+ function logVerbose(message) {
293
+ if (process.env.CLAUDE_HOOK_VERBOSE === '1') {
294
+ console.error(message);
295
+ }
296
+ }
297
+
298
+ /**
299
+ * Output to stdout (returned to Claude)
300
+ */
301
+ function output(data) {
302
+ if (typeof data === 'object') {
303
+ console.log(JSON.stringify(data));
304
+ } else {
305
+ console.log(data);
306
+ }
307
+ }
308
+
309
+ /**
310
+ * Read a text file safely
311
+ */
312
+ function readFile(filePath) {
313
+ try {
314
+ return fs.readFileSync(filePath, 'utf8');
315
+ } catch {
316
+ return null;
317
+ }
318
+ }
319
+
320
+ /**
321
+ * Write a text file
322
+ */
323
+ function writeFile(filePath, content) {
324
+ ensureDir(path.dirname(filePath));
325
+ fs.writeFileSync(filePath, content, 'utf8');
326
+ }
327
+
328
+ /**
329
+ * Append to a text file
330
+ */
331
+ function appendFile(filePath, content) {
332
+ ensureDir(path.dirname(filePath));
333
+ fs.appendFileSync(filePath, content, 'utf8');
334
+ }
335
+
336
+ /**
337
+ * Check if a command exists in PATH
338
+ * Uses execFileSync to prevent command injection
339
+ */
340
+ function commandExists(cmd) {
341
+ // Validate command name - only allow alphanumeric, dash, underscore, dot
342
+ if (!/^[a-zA-Z0-9_.-]+$/.test(cmd)) {
343
+ return false;
344
+ }
345
+
346
+ try {
347
+ if (isWindows) {
348
+ // Use spawnSync to avoid shell interpolation
349
+ const result = spawnSync('where', [cmd], { stdio: 'pipe' });
350
+ return result.status === 0;
351
+ } else {
352
+ const result = spawnSync('which', [cmd], { stdio: 'pipe' });
353
+ return result.status === 0;
354
+ }
355
+ } catch {
356
+ return false;
357
+ }
358
+ }
359
+
360
+ /**
361
+ * Run a command and return output
362
+ *
363
+ * SECURITY NOTE: This function executes shell commands. Only use with
364
+ * trusted, hardcoded commands. Never pass user-controlled input directly.
365
+ * For user input, use runCommandSafe() with argument arrays instead.
366
+ *
367
+ * @param {string} cmd - Command to execute (should be trusted/hardcoded)
368
+ * @param {object} options - execSync options
369
+ */
370
+ function runCommand(cmd, options = {}) {
371
+ try {
372
+ const result = execSync(cmd, {
373
+ encoding: 'utf8',
374
+ stdio: ['pipe', 'pipe', 'pipe'],
375
+ ...options
376
+ });
377
+ return { success: true, output: result.trim() };
378
+ } catch (err) {
379
+ return { success: false, output: err.stderr || err.message };
380
+ }
381
+ }
382
+
383
+ /**
384
+ * Run a command safely using spawnSync with argument arrays (no shell).
385
+ * Prevents command injection when arguments contain untrusted data
386
+ * (e.g., file paths from hook payloads).
387
+ *
388
+ * @param {string} cmd - Executable name (e.g., 'clang-format')
389
+ * @param {string[]} args - Array of arguments
390
+ * @param {object} options - spawnSync options (cwd, timeout, etc.)
391
+ * @returns {{ success: boolean, output: string }}
392
+ */
393
+ function runCommandSafe(cmd, args = [], options = {}) {
394
+ try {
395
+ const result = spawnSync(cmd, args, {
396
+ encoding: 'utf8',
397
+ stdio: ['pipe', 'pipe', 'pipe'],
398
+ ...options
399
+ });
400
+ if (result.error) {
401
+ // Timeout or spawn failure
402
+ const msg = result.error.code === 'ETIMEDOUT'
403
+ ? `ETIMEDOUT: ${cmd} timed out`
404
+ : result.error.message;
405
+ return { success: false, output: msg };
406
+ }
407
+ if (result.status === 0) {
408
+ return { success: true, output: (result.stdout || '').trim() };
409
+ }
410
+ return { success: false, output: (result.stderr || result.stdout || '').trim() };
411
+ } catch (err) {
412
+ return { success: false, output: err.message };
413
+ }
414
+ }
415
+
416
+ /**
417
+ * Check if current directory is a git repository
418
+ */
419
+ function isGitRepo() {
420
+ return runCommand('git rev-parse --git-dir').success;
421
+ }
422
+
423
+ /**
424
+ * Get git modified files, optionally filtered by regex patterns
425
+ * @param {string[]} patterns - Array of regex pattern strings to filter files.
426
+ * Invalid patterns are silently skipped.
427
+ * @returns {string[]} Array of modified file paths
428
+ */
429
+ function getGitModifiedFiles(patterns = []) {
430
+ if (!isGitRepo()) return [];
431
+
432
+ const result = runCommand('git diff --name-only HEAD');
433
+ if (!result.success) return [];
434
+
435
+ let files = result.output.split('\n').filter(Boolean);
436
+
437
+ if (patterns.length > 0) {
438
+ // Pre-compile patterns, skipping invalid ones
439
+ const compiled = [];
440
+ for (const pattern of patterns) {
441
+ if (typeof pattern !== 'string' || pattern.length === 0) continue;
442
+ try {
443
+ compiled.push(new RegExp(pattern));
444
+ } catch {
445
+ // Skip invalid regex patterns
446
+ }
447
+ }
448
+ if (compiled.length > 0) {
449
+ files = files.filter(file => compiled.some(regex => regex.test(file)));
450
+ }
451
+ }
452
+
453
+ return files;
454
+ }
455
+
456
+ /**
457
+ * Replace text in a file (cross-platform sed alternative)
458
+ * @param {string} filePath - Path to the file
459
+ * @param {string|RegExp} search - Pattern to search for. String patterns replace
460
+ * the FIRST occurrence only; use a RegExp with the `g` flag for global replacement.
461
+ * @param {string} replace - Replacement string
462
+ * @param {object} options - Options
463
+ * @param {boolean} options.all - When true and search is a string, replaces ALL
464
+ * occurrences (uses String.replaceAll). Ignored for RegExp patterns.
465
+ * @returns {boolean} true if file was written, false on error
466
+ */
467
+ function replaceInFile(filePath, search, replace, options = {}) {
468
+ const content = readFile(filePath);
469
+ if (content === null) return false;
470
+
471
+ try {
472
+ let newContent;
473
+ if (options.all && typeof search === 'string') {
474
+ newContent = content.replaceAll(search, replace);
475
+ } else {
476
+ newContent = content.replace(search, replace);
477
+ }
478
+ writeFile(filePath, newContent);
479
+ return true;
480
+ } catch (err) {
481
+ log(`[Utils] replaceInFile failed for ${filePath}: ${err.message}`);
482
+ return false;
483
+ }
484
+ }
485
+
486
+ /**
487
+ * Count occurrences of a pattern in a file
488
+ * @param {string} filePath - Path to the file
489
+ * @param {string|RegExp} pattern - Pattern to count. Strings are treated as
490
+ * global regex patterns. RegExp instances are used as-is but the global
491
+ * flag is enforced to ensure correct counting.
492
+ * @returns {number} Number of matches found
493
+ */
494
+ function countInFile(filePath, pattern) {
495
+ const content = readFile(filePath);
496
+ if (content === null) return 0;
497
+
498
+ let regex;
499
+ try {
500
+ if (pattern instanceof RegExp) {
501
+ // Always create new RegExp to avoid shared lastIndex state; ensure global flag
502
+ regex = new RegExp(pattern.source, pattern.flags.includes('g') ? pattern.flags : pattern.flags + 'g');
503
+ } else if (typeof pattern === 'string') {
504
+ regex = new RegExp(pattern, 'g');
505
+ } else {
506
+ return 0;
507
+ }
508
+ } catch {
509
+ return 0; // Invalid regex pattern
510
+ }
511
+ const matches = content.match(regex);
512
+ return matches ? matches.length : 0;
513
+ }
514
+
515
+ /**
516
+ * Search for pattern in file and return matching lines with line numbers
517
+ */
518
+ function grepFile(filePath, pattern) {
519
+ const content = readFile(filePath);
520
+ if (content === null) return [];
521
+
522
+ let regex;
523
+ try {
524
+ if (pattern instanceof RegExp) {
525
+ // Always create a new RegExp without the 'g' flag to prevent lastIndex
526
+ // state issues when using .test() in a loop (g flag makes .test() stateful,
527
+ // causing alternating match/miss on consecutive matching lines)
528
+ const flags = pattern.flags.replace('g', '');
529
+ regex = new RegExp(pattern.source, flags);
530
+ } else {
531
+ regex = new RegExp(pattern);
532
+ }
533
+ } catch {
534
+ return []; // Invalid regex pattern
535
+ }
536
+ const lines = content.split('\n');
537
+ const results = [];
538
+
539
+ lines.forEach((line, index) => {
540
+ if (regex.test(line)) {
541
+ results.push({ lineNumber: index + 1, content: line });
542
+ }
543
+ });
544
+
545
+ return results;
546
+ }
547
+
548
+ module.exports = {
549
+ // Platform info
550
+ isWindows,
551
+ isMacOS,
552
+ isLinux,
553
+
554
+ // Directories
555
+ getHomeDir,
556
+ getClaudeDir,
557
+ getSessionsDir,
558
+ getLearnedSkillsDir,
559
+ getTempDir,
560
+ ensureDir,
561
+
562
+ // Date/Time
563
+ getDateString,
564
+ getTimeString,
565
+ getDateTimeString,
566
+
567
+ // Session/Project
568
+ getSessionIdShort,
569
+ getGitRepoName,
570
+ getProjectName,
571
+
572
+ // File operations
573
+ findFiles,
574
+ readFile,
575
+ writeFile,
576
+ appendFile,
577
+ replaceInFile,
578
+ countInFile,
579
+ grepFile,
580
+
581
+ // Hook I/O
582
+ readStdinJson,
583
+ log,
584
+ logVerbose,
585
+ output,
586
+
587
+ // System
588
+ commandExists,
589
+ runCommand,
590
+ runCommandSafe,
591
+ isGitRepo,
592
+ getGitModifiedFiles
593
+ };