All files utils.ts

95.65% Statements 88/92
84.78% Branches 39/46
93.33% Functions 14/15
96.59% Lines 85/88

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 1926x 6x 6x 6x 6x     6x             6x 6x     23x 11x 11x   12x         4x 1x         4x 2x         64x 63x         2x 2x             6x 12x 2x     10x   10x 1x     9x 9x 6x     6x   3x       6x 15x 1x     14x     14x 1x     13x 1x     12x 1x     11x 3x           8x     6x 4x   4x 4x 2x     4x 4x 2x     4x         6x 6x     117x 1x   116x     116x 58x 58x 83x   58x     6x 41x 1x     40x 1x       39x 39x   2x       37x 121x 59x     62x 183x 3x       59x 84x         59x     37x 3x       34x 1x     33x        
export 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') {
      const lowerLevel = level.toLowerCase();
      Logger.minLevel = SEVERITY_ORDER[lowerLevel] ?? LogLevel.DEBUG;
    } else {
      Logger.minLevel = level;
    }
  }
 
  static debug(message: string, category: string = 'general'): void {
    if (LogLevel.DEBUG >= Logger.minLevel) {
      console.debug(`[${category}] DEBUG: ${message}`);
    }
  }
 
  static info(message: string, category: string = 'general'): void {
    if (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 {
    if (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, underscores, and colons',
    };
  }
 
  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 in object keys only
  const checkDangerousPatterns = (obj: unknown): boolean => {
    if (typeof obj !== 'object' || obj === null) {
      return false;
    }
 
    const dangerousKeys = ['constructor', 'prototype', '__proto__'];
    if (dangerousKeys.some((key) => Object.keys(obj).includes(key))) {
      return true;
    }
 
    // Recursively check nested objects
    for (const key in obj as Record<string, unknown>) {
      Iif (checkDangerousPatterns((obj as Record<string, unknown>)[key])) {
        return true;
      }
    }
 
    return false;
  };
 
  if (checkDangerousPatterns(parsed)) {
    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;
}
 
// ==================== Markdown Utilities ====================