All files utils.ts

81.05% Statements 77/95
70.83% Branches 34/48
52.94% Functions 9/17
81.52% Lines 75/92

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210        5x 5x 5x 5x 5x     5x             5x 5x                                             54x 54x                         5x 12x 2x     10x   10x 1x     9x 9x 6x     6x   3x       5x 15x 1x     14x     14x 1x     13x 1x     12x 1x     11x 3x           8x     5x 4x   4x 4x 2x     4x 4x 2x     4x         5x 5x     107x 1x   106x     106x 54x 54x 77x   52x     5x 38x 1x     37x 1x       36x 36x   2x       34x 34x           4x       30x 1x     29x         5x             5x             5x 6x 6x 4x   2x           5x      
// src/utils.ts
 
// ==================== Logger ====================
 
enum LogLevel {
  DEBUG = 0,
  INFO = 1,
  WARN = 2,
  ERROR = 3,
}
 
const SEVERITY_ORDER: Record<string, number> = {
  debug: LogLevel.DEBUG,
  info: LogLevel.INFO,
  warn: LogLevel.WARN,
  error: LogLevel.ERROR,
};
 
export class Logger {
  private static minLevel: LogLevel = LogLevel.DEBUG;
 
  static setLevel(level: string | LogLevel): void {
    if (typeof level === 'string') {
      Logger.minLevel = SEVERITY_ORDER[level.toLowerCase()] ?? LogLevel.DEBUG;
    } else {
      Logger.minLevel = level;
    }
  }
 
  static debug(message: string, category: string = 'general'): void {
    Iif (LogLevel.DEBUG >= Logger.minLevel) {
      console.debug(`[${category}] DEBUG: ${message}`);
    }
  }
 
  static info(message: string, category: string = 'general'): void {
    Iif (LogLevel.INFO >= Logger.minLevel) {
      console.info(`[${category}] INFO: ${message}`);
    }
  }
 
  static warn(message: string, category: string = 'general'): void {
    if (LogLevel.WARN >= Logger.minLevel) {
      console.warn(`[${category}] WARN: ${message}`);
    }
  }
 
  static error(message: string, category: string = 'general'): void {
    Iif (LogLevel.ERROR >= Logger.minLevel) {
      console.error(`[${category}] ERROR: ${message}`);
    }
  }
}
 
// ==================== URL & Model Validation ====================
 
export function validateOllamaUrl(url: string): { valid: boolean; error?: string } {
  if (typeof url !== 'string' || !url.trim()) {
    return { valid: false, error: 'URL cannot be empty' };
  }
 
  const trimmedUrl = url.trim();
 
  if (trimmedUrl.endsWith('/')) {
    return { valid: false, error: 'URL should not end with a slash' };
  }
 
  try {
    const parsed = new URL(trimmedUrl);
    Iif (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
      return { valid: false, error: 'Must be a valid HTTP or HTTPS URL' };
    }
    return { valid: true };
  } catch {
    return { valid: false, error: 'Must be a valid HTTP or HTTPS URL' };
  }
}
 
export function validateModelName(model: string): { valid: boolean; error?: string } {
  if (typeof model !== 'string') {
    return { valid: false, error: 'Model name must be a string' };
  }
 
  const trimmedModel = model.trim();
 
  // Explicit check for empty string after trimming
  if (!trimmedModel || trimmedModel.length === 0) {
    return { valid: false, error: 'Model name cannot be empty' };
  }
 
  if (trimmedModel.length < 2) {
    return { valid: false, error: 'Model name must be at least 2 characters long' };
  }
 
  if (trimmedModel.length > 100) {
    return { valid: false, error: 'Model name must be less than 100 characters long' };
  }
 
  if (!/^[a-zA-Z0-9._-]+$/.test(trimmedModel)) {
    return {
      valid: false,
      error: 'Model name can only contain letters, numbers, dots, dashes, and underscores',
    };
  }
 
  return { valid: true };
}
 
export function validatePluginSettings(settings: { ollamaUrl: string; model: string }): string[] {
  const errors: string[] = [];
 
  const urlValidation = validateOllamaUrl(settings.ollamaUrl);
  if (!urlValidation.valid) {
    errors.push(`Invalid Ollama URL: ${urlValidation.error}`);
  }
 
  const modelValidation = validateModelName(settings.model);
  if (!modelValidation.valid) {
    errors.push(`Invalid Model Name: ${modelValidation.error}`);
  }
 
  return errors;
}
 
// ==================== Safe JSON Parsing ====================
 
const MAX_JSON_SIZE = 1_000_000;
const MAX_JSON_NESTING = 24;
 
function countNestingDepth(value: unknown, depth: number = 0): number {
  if (depth > MAX_JSON_NESTING) {
    return depth;
  }
  Iif (Array.isArray(value)) {
    return Math.max(...value.map((item) => countNestingDepth(item, depth + 1)), depth);
  }
  if (value !== null && typeof value === 'object') {
    const entries = Object.values(value as Record<string, unknown>);
    if (entries.length === 0) return depth;
    return Math.max(...entries.map((item) => countNestingDepth(item, depth + 1)), depth);
  }
  return depth;
}
 
export function safeParseJson(jsonString: string): unknown {
  if (typeof jsonString !== 'string') {
    throw new Error('Input must be a string');
  }
 
  if (jsonString.length > MAX_JSON_SIZE) {
    throw new Error('JSON input too large');
  }
 
  let parsed: unknown;
  try {
    parsed = JSON.parse(jsonString);
  } catch {
    throw new Error('Invalid JSON');
  }
 
  // Check for dangerous prototype pollution patterns
  const reStringified = JSON.stringify(parsed);
  if (
    reStringified.includes('constructor') ||
    reStringified.includes('prototype') ||
    reStringified.includes('__proto__') ||
    reStringified.includes('function')
  ) {
    throw new Error('dangerous code pattern detected');
  }
 
  // Check nesting depth
  if (countNestingDepth(parsed) > MAX_JSON_NESTING) {
    throw new Error('JSON nesting too deep');
  }
 
  return parsed;
}
 
// ==================== Path & File Utilities ====================
 
export function sanitizeFilePath(path: string): string {
  Iif (path.includes('..')) {
    throw new Error('Invalid path - cannot contain .. segments');
  }
  return path;
}
 
export async function safeWriteFile(filePath: string, content: string): Promise<void> {
  const sanitizedPath = sanitizeFilePath(filePath);
  console.log(`Writing to ${sanitizedPath}:`, content);
}
 
// ==================== HTTP Helpers ====================
 
export function isValidHttpUrl(url: string): boolean {
  try {
    const parsed = new URL(url);
    return parsed.protocol === 'http:' || parsed.protocol === 'https:';
  } catch {
    return false;
  }
}
 
// ==================== Markdown Utilities ====================
 
export function convertMarkdownToHtml(markdown: string): string {
  return markdown.replace(/\n/g, '<br>').replace(/# (.+)/g, '<h1>$1</h1>');
}