All files / src crawl4ai-service.ts

95.72% Statements 112/117
91.02% Branches 71/78
100% Functions 14/14
95.72% Lines 112/117

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 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338                                          3x   22x 3x       19x 2x         17x 3x       14x       14x       3x 45x 45x 39x   6x         3x 25x 25x     25x 2x     23x 2x       21x 2x     19x 2x     17x 2x     15x 2x       13x 11x 11x 11x 11x       2x 2x                       85x                       17x 2x     15x 15x             3x   12x           4x 1x     3x 3x           1x   2x           3x 1x     2x 2x         1x   1x           13x 1x       12x     12x 14x 6x           6x 6x           3x   3x           5x 2x       3x     3x 1x     3x 1x     3x 3x           3x               5x 1x     4x 4x         2x   2x         2x   2x 1x   1x         3x   3x 2x   1x           30x 5x       5x 8x 2x               28x   28x           28x 28x 25x   3x           3x       3x 3x 3x 3x 1x     2x 2x 2x     2x 1x         1x        
import axios, { AxiosInstance, AxiosError } from 'axios';
import {
  BatchCrawlOptions,
  AdvancedCrawlConfig,
  CrawlEndpointOptions,
  CrawlEndpointResponse,
  JSExecuteEndpointOptions,
  JSExecuteEndpointResponse,
  ScreenshotEndpointOptions,
  ScreenshotEndpointResponse,
  PDFEndpointOptions,
  PDFEndpointResponse,
  HTMLEndpointOptions,
  HTMLEndpointResponse,
  MarkdownEndpointOptions,
  MarkdownEndpointResponse,
  LLMEndpointOptions,
  LLMEndpointResponse,
} from './types.js';
 
// Helper to validate JavaScript code
const validateJavaScriptCode = (code: string): boolean => {
  // Check for common HTML entities that shouldn't be in JS
  if (/"|&|<|>|&#\d+;|&\w+;/.test(code)) {
    return false;
  }
 
  // Basic check to ensure it's not HTML
  if (/<(!DOCTYPE|html|body|head|script|style)\b/i.test(code)) {
    return false;
  }
 
  // Check for literal \n, \t, \r outside of strings (common LLM mistake)
  // Look for patterns like: ;\n or }\n or )\n which suggest literal newlines
  if (/[;})]\s*\\n|\\n\s*[{(/]/.test(code)) {
    return false;
  }
 
  // Check for obvious cases of literal \n between statements
  Iif (/[;})]\s*\\n\s*\w/.test(code)) {
    return false;
  }
 
  return true;
};
 
// Helper to validate URL format
const validateURL = (url: string): boolean => {
  try {
    new URL(url);
    return true;
  } catch {
    return false;
  }
};
 
// Helper to handle axios errors consistently
const handleAxiosError = (error: unknown): never => {
  Eif (axios.isAxiosError(error)) {
    const axiosError = error as AxiosError;
 
    // Handle timeout errors
    if (axiosError.code === 'ECONNABORTED') {
      throw new Error('Request timed out');
    }
 
    if (axiosError.code === 'ETIMEDOUT') {
      throw new Error('Request timeout');
    }
 
    // Handle network errors
    if (axiosError.code === 'ENOTFOUND') {
      throw new Error(`DNS resolution failed: ${axiosError.message}`);
    }
 
    if (axiosError.code === 'ECONNREFUSED') {
      throw new Error(`Connection refused: ${axiosError.message}`);
    }
 
    if (axiosError.code === 'ECONNRESET') {
      throw new Error(`Connection reset: ${axiosError.message}`);
    }
 
    if (axiosError.code === 'ENETUNREACH') {
      throw new Error(`Network unreachable: ${axiosError.message}`);
    }
 
    // Handle HTTP errors
    if (axiosError.response) {
      const status = axiosError.response.status;
      const data = axiosError.response.data as any; // eslint-disable-line @typescript-eslint/no-explicit-any
      const message = data?.error || data?.detail || data?.message || axiosError.message;
      throw new Error(`Request failed with status ${status}: ${message}`);
    }
 
    // Handle request errors (e.g., invalid URL)
    Eif (axiosError.request) {
      throw new Error(`Request failed: ${axiosError.message}`);
    }
  }
 
  // Re-throw unknown errors
  throw error;
};
 
export class Crawl4AIService {
  private axiosClient: AxiosInstance;
 
  constructor(baseURL: string, apiKey: string) {
    this.axiosClient = axios.create({
      baseURL,
      headers: {
        'X-API-Key': apiKey,
        'Content-Type': 'application/json',
      },
      timeout: 120000,
    });
  }
 
  async getMarkdown(options: MarkdownEndpointOptions): Promise<MarkdownEndpointResponse> {
    // Validate URL
    if (!validateURL(options.url)) {
      throw new Error('Invalid URL format');
    }
 
    try {
      const response = await this.axiosClient.post('/md', {
        url: options.url,
        f: options.f,
        q: options.q,
        c: options.c,
      });
 
      return response.data;
    } catch (error) {
      return handleAxiosError(error);
    }
  }
 
  async captureScreenshot(options: ScreenshotEndpointOptions): Promise<ScreenshotEndpointResponse> {
    // Validate URL
    if (!validateURL(options.url)) {
      throw new Error('Invalid URL format');
    }
 
    try {
      const response = await this.axiosClient.post('/screenshot', {
        url: options.url,
        screenshot_wait_for: options.screenshot_wait_for,
        // output_path is omitted to get base64 response
      });
 
      return response.data;
    } catch (error) {
      return handleAxiosError(error);
    }
  }
 
  async generatePDF(options: PDFEndpointOptions): Promise<PDFEndpointResponse> {
    // Validate URL
    if (!validateURL(options.url)) {
      throw new Error('Invalid URL format');
    }
 
    try {
      const response = await this.axiosClient.post('/pdf', {
        url: options.url,
        // output_path is omitted to get base64 response
      });
 
      return response.data;
    } catch (error) {
      return handleAxiosError(error);
    }
  }
 
  async executeJS(options: JSExecuteEndpointOptions): Promise<JSExecuteEndpointResponse> {
    // Validate URL
    if (!validateURL(options.url)) {
      throw new Error('Invalid URL format');
    }
 
    // Ensure scripts is always an array
    const scripts = Array.isArray(options.scripts) ? options.scripts : [options.scripts];
 
    // Validate each script
    for (const script of scripts) {
      if (!validateJavaScriptCode(script)) {
        throw new Error(
          'Invalid JavaScript: Contains HTML entities (&quot;), literal \\n outside strings, or HTML tags. Use proper JS syntax with real quotes and newlines.',
        );
      }
    }
 
    try {
      const response = await this.axiosClient.post('/execute_js', {
        url: options.url,
        scripts: scripts, // Always send as array
        // Only url and scripts are supported by the endpoint
      });
 
      return response.data;
    } catch (error) {
      return handleAxiosError(error);
    }
  }
 
  async batchCrawl(options: BatchCrawlOptions) {
    // Validate URLs
    if (!options.urls || options.urls.length === 0) {
      throw new Error('URLs array cannot be empty');
    }
 
    // Build crawler config if needed
    const crawler_config: Record<string, unknown> = {};
 
    // Handle remove_images by using exclude_tags
    if (options.remove_images) {
      crawler_config.exclude_tags = ['img', 'picture', 'svg'];
    }
 
    if (options.bypass_cache) {
      crawler_config.cache_mode = 'BYPASS';
    }
 
    try {
      const response = await this.axiosClient.post('/crawl', {
        urls: options.urls,
        max_concurrent: options.max_concurrent,
        crawler_config: Object.keys(crawler_config).length > 0 ? crawler_config : undefined,
      });
 
      return response.data;
    } catch (error) {
      return handleAxiosError(error);
    }
  }
 
  async getHTML(options: HTMLEndpointOptions): Promise<HTMLEndpointResponse> {
    // Validate URL
    if (!validateURL(options.url)) {
      throw new Error('Invalid URL format');
    }
 
    try {
      const response = await this.axiosClient.post('/html', {
        url: options.url,
        // Only url is supported by the endpoint
      });
 
      return response.data;
    } catch (error) {
      return handleAxiosError(error);
    }
  }
 
  async parseSitemap(url: string) {
    try {
      // Use axios directly without baseURL for fetching external URLs
      const response = await axios.get(url);
      return response.data;
    } catch (error) {
      return handleAxiosError(error);
    }
  }
 
  async detectContentType(url: string): Promise<string> {
    try {
      // Use axios directly without baseURL for external URLs
      const response = await axios.head(url);
      return response.headers['content-type'] || '';
    } catch {
      return '';
    }
  }
 
  async crawl(options: AdvancedCrawlConfig): Promise<CrawlEndpointResponse> {
    // Validate JS code if present
    if (options.crawler_config?.js_code) {
      const scripts = Array.isArray(options.crawler_config.js_code)
        ? options.crawler_config.js_code
        : [options.crawler_config.js_code];
 
      for (const script of scripts) {
        if (!validateJavaScriptCode(script)) {
          throw new Error(
            'Invalid JavaScript: Contains HTML entities (&quot;), literal \\n outside strings, or HTML tags. Use proper JS syntax with real quotes and newlines.',
          );
        }
      }
    }
 
    // Server only accepts urls array, not url string
    const urls = options.url ? [options.url] : options.urls || [];
 
    const requestBody: CrawlEndpointOptions = {
      urls,
      browser_config: options.browser_config,
      crawler_config: options.crawler_config || {}, // Always include crawler_config, even if empty
    };
 
    try {
      const response = await this.axiosClient.post('/crawl', requestBody);
      return response.data;
    } catch (error) {
      return handleAxiosError(error);
    }
  }
 
  async extractWithLLM(options: LLMEndpointOptions): Promise<LLMEndpointResponse> {
    // Validate URL
    Iif (!validateURL(options.url)) {
      throw new Error('Invalid URL format');
    }
 
    try {
      const encodedUrl = encodeURIComponent(options.url);
      const encodedQuery = encodeURIComponent(options.query);
      const response = await this.axiosClient.get(`/llm/${encodedUrl}?q=${encodedQuery}`);
      return response.data;
    } catch (error) {
      // Special handling for LLM-specific errors
      Eif (axios.isAxiosError(error)) {
        const axiosError = error as AxiosError;
        Iif (axiosError.code === 'ECONNABORTED' || axiosError.response?.status === 504) {
          throw new Error('LLM extraction timed out. Try a simpler query or different URL.');
        }
        if (axiosError.response?.status === 401) {
          throw new Error(
            'LLM extraction failed: No LLM provider configured on server. Please ensure the server has an API key set.',
          );
        }
      }
      return handleAxiosError(error);
    }
  }
}