All files / services/ai claude.service.ts

100% Statements 151/151
100% Branches 104/104
100% Functions 19/19
100% Lines 150/150

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 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655                                                                                                                                                          21x     21x 21x   21x 1x         20x 20x   20x 20x 9x     11x 11x 8x       3x                       21x 21x 21x   21x 1557x     1557x 238x 238x 238x       1319x 2x 2x 2x     1317x 2x 2x 2x       1315x 973x   1x 1x   1x 1x   1x 1x   1x 1x   1x 1x     968x 968x   1x   967x           342x       21x           3x             3x                                 52x 1x   51x                             52x 52x 52x 52x                           49x                             43x 7x 7x             7x 2x       5x 2x       3x 1x       2x 1x         1x         36x           14x 14x   14x       14x           14x                       7x             14x   14x           14x     7x         7x       7x   7x                   4x 4x   4x                         2x   4x     2x     2x 2x             4x 4x   4x                         3x       4x   4x 4x 4x                       1x           1x       2x     2x 2x                   7x 7x           6x 7x 7x             7x 7x           6x           13x 13x   13x                         12x         13x         13x   13x 13x       13x 13x               2x           2x       3x     3x 3x                           2x               1x               1x 1x   1x                   1x                                   1x       1x                   60x 60x   60x     60x 7x     7x       53x 1x     1x           52x 52x           52x             3x    
import type {
	DraftPromptParams,
	RewritePromptParams,
	MetaPromptParams,
	TopicSuggestionPromptParams,
} from "./prompts";
import {
	buildDraftPrompt,
	buildRewritePrompt,
	buildMetaPrompt,
	buildTopicSuggestionPrompt,
} from "./prompts";
 
/**
 * Response types for AI service methods
 */
export interface GenerateDraftResponse {
	content: string; // Markdown content
}
 
export interface RewriteSectionResponse {
	revisedContent: string; // Markdown content
}
 
export interface GenerateMetaResponse {
	title: string;
	meta_description: string;
	suggested_slug: string;
}
 
export interface TopicSuggestion {
	title: string;
	blog_type: "general" | "project_spotlight" | "hybrid";
	primary_keyword: string;
	secondary_keywords: string[];
	outline: string;
	seo_value: string;
	pro_angle?: string;
}
 
export interface SuggestTopicsResponse {
	suggestions: TopicSuggestion[];
}
 
/**
 * Claude API response structure
 */
interface ClaudeAPIResponse {
	content: Array<{ type: string; text: string }>;
	[key: string]: unknown;
}
 
/**
 * AI Service interface
 */
export interface AIService {
	generateDraft(params: DraftPromptParams): Promise<GenerateDraftResponse>;
	rewriteSection(params: RewritePromptParams): Promise<RewriteSectionResponse>;
	generateMeta(params: MetaPromptParams): Promise<GenerateMetaResponse>;
	suggestTopics(
		params: TopicSuggestionPromptParams,
	): Promise<SuggestTopicsResponse>;
	/** General-purpose JSON generation — sends a prompt, parses JSON response */
	generateJSON<T>(prompt: string, options?: { model?: "opus" | "haiku"; maxTokens?: number; temperature?: number }): Promise<T>;
	/** Generate free-form text content from a prompt */
	generateText(prompt: string, options?: { model?: "opus" | "haiku"; maxTokens?: number; temperature?: number }): Promise<string>;
}
 
/**
 * Extract JSON from Claude API response that may be wrapped in markdown code blocks
 * Handles formats like:
 * - ```json\n{...}\n```
 * - ```\n{...}\n```
 * - Plain JSON: {...}
 * - Text before/after JSON: "Here's the response:\n{...}\n"
 */
function extractJSON(text: string): string {
	const trimmed = text.trim();
 
	// Try to extract from markdown code blocks first
	const codeBlockPattern = /```(?:json)?\s*\n?([\s\S]*?)\n?```/;
	const codeBlockMatch = trimmed.match(codeBlockPattern);
 
	if (codeBlockMatch?.[1]) {
		return sanitizeJSON(codeBlockMatch[1].trim());
	}
 
	// Try to find JSON array or object in the text
	// Look for patterns starting with [ or {
	const jsonArrayPattern = /(\[[\s\S]*\])/;
	const jsonObjectPattern = /(\{[\s\S]*\})/;
 
	const arrayMatch = trimmed.match(jsonArrayPattern);
	if (arrayMatch?.[1]) {
		return sanitizeJSON(arrayMatch[1].trim());
	}
 
	const objectMatch = trimmed.match(jsonObjectPattern);
	if (objectMatch?.[1]) {
		return sanitizeJSON(objectMatch[1].trim());
	}
 
	// Fall back to trimmed original text
	return sanitizeJSON(trimmed);
}
 
/**
 * Sanitize JSON string by escaping control characters within string values.
 * This fixes issues where Claude returns JSON with unescaped newlines/tabs
 * inside string values, which breaks JSON.parse().
 *
 * Strategy: Replace literal control characters with their escaped versions,
 * but only within quoted strings (not in structural JSON).
 */
function sanitizeJSON(jsonText: string): string {
	let result = "";
	let inString = false;
	let escaped = false;
 
	for (let i = 0; i < jsonText.length; i++) {
		const char = jsonText[i];
 
		// Track if we're inside a string
		if (char === '"' && !escaped) {
			inString = !inString;
			result += char;
			continue;
		}
 
		// Track escape sequences
		if (char === "\\" && !escaped) {
			escaped = true;
			result += char;
			continue;
		}
 
		if (escaped) {
			escaped = false;
			result += char;
			continue;
		}
 
		// If we're inside a string, escape control characters
		if (inString) {
			switch (char) {
				case "\n":
					result += "\\n";
					break;
				case "\r":
					result += "\\r";
					break;
				case "\t":
					result += "\\t";
					break;
				case "\b":
					result += "\\b";
					break;
				case "\f":
					result += "\\f";
					break;
				default: {
					// Check for other control characters (ASCII 0-31)
					const code = char.charCodeAt(0);
					if (code < 32 && code !== 10 && code !== 13 && code !== 9) {
						// Escape as unicode
						result += `\\u${code.toString(16).padStart(4, "0")}`;
					} else {
						result += char;
					}
				}
			}
		} else {
			// Outside strings, preserve as-is
			result += char;
		}
	}
 
	return result;
}
 
/**
 * Claude API configuration
 */
const CLAUDE_MODELS = {
	// Use Opus 4.5 for content generation (drafts, rewrites) - latest model with best quality
	OPUS: "claude-opus-4-5-20251101",
	// Use Haiku 4.5 for faster, cheaper operations (meta, suggestions)
	HAIKU: "claude-haiku-4-5-20251001",
} as const;
 
const MAX_TOKENS = {
	DRAFT: 4096, // Full blog content
	REWRITE: 2048, // Section rewrite
	META: 512, // Short metadata
	TOPICS: 2048, // Topic suggestions list
} as const;
 
/**
 * Build the Claude API endpoint URL.
 * If AI Gateway is configured (both CLOUDFLARE_ACCOUNT_ID and AI_GATEWAY_SLUG set),
 * routes through Cloudflare AI Gateway for caching, analytics, and rate limiting.
 * Otherwise falls back to direct Anthropic API.
 */
function getClaudeApiUrl(env?: {
	CLOUDFLARE_ACCOUNT_ID?: string;
	AI_GATEWAY_SLUG?: string;
}): string {
	if (env?.CLOUDFLARE_ACCOUNT_ID && env?.AI_GATEWAY_SLUG) {
		return `https://gateway.ai.cloudflare.com/v1/${env.CLOUDFLARE_ACCOUNT_ID}/${env.AI_GATEWAY_SLUG}/anthropic/v1/messages`;
	}
	return "https://api.anthropic.com/v1/messages";
}
 
/**
 * Real Claude API implementation using direct fetch for Cloudflare Workers compatibility.
 * Supports optional Cloudflare AI Gateway for caching, analytics, and rate limiting.
 */
class ClaudeAIService implements AIService {
	private apiKey: string;
	private apiUrl: string;
 
	constructor(
		apiKey: string,
		env?: { CLOUDFLARE_ACCOUNT_ID?: string; AI_GATEWAY_SLUG?: string },
	) {
		this.apiKey = apiKey;
		this.apiUrl = getClaudeApiUrl(env);
		const usingGateway = this.apiUrl.includes("gateway.ai.cloudflare.com");
		console.log(
			`[ClaudeAIService] Service initialized (AI Gateway: ${usingGateway ? "enabled" : "disabled"})`,
		);
	}
 
	/**
	 * Call Claude API using fetch for better Cloudflare Workers compatibility
	 */
	private async callClaudeAPI(
		model: string,
		maxTokens: number,
		temperature: number,
		messages: Array<{ role: string; content: string }>,
	): Promise<ClaudeAPIResponse> {
		const response = await fetch(this.apiUrl, {
			method: "POST",
			headers: {
				"Content-Type": "application/json",
				"x-api-key": this.apiKey,
				"anthropic-version": "2023-06-01",
			},
			body: JSON.stringify({
				model,
				max_tokens: maxTokens,
				temperature,
				messages,
			}),
		});
 
		if (!response.ok) {
			const errorBody = await response.text();
			console.error("[ClaudeAPI] API call failed:", {
				status: response.status,
				statusText: response.statusText,
				body: errorBody,
			});
 
			// Provide specific error messages based on status code
			if (response.status === 401 || response.status === 403) {
				throw new Error(
					"AI service authentication failed. Please verify CLAUDE_API_KEY is correct.",
				);
			}
			if (response.status === 429) {
				throw new Error(
					"AI service rate limit exceeded. Please try again in a few minutes.",
				);
			}
			if (response.status === 503 || response.status === 502) {
				throw new Error(
					"AI service temporarily unavailable. Please try again later.",
				);
			}
			if (response.status === 400) {
				throw new Error(
					`Invalid request to AI service: ${errorBody.substring(0, 100)}`,
				);
			}
 
			throw new Error(
				`Claude API error: ${response.status} ${response.statusText}`,
			);
		}
 
		return response.json();
	}
 
	async generateDraft(
		params: DraftPromptParams,
	): Promise<GenerateDraftResponse> {
		try {
			const prompt = buildDraftPrompt(params);
 
			console.log(
				"[generateDraft] Starting AI draft generation with model:",
				CLAUDE_MODELS.OPUS,
			);
			console.log(
				"[generateDraft] Prompt length:",
				prompt.length,
				"characters",
			);
 
			const response = await this.callClaudeAPI(
				CLAUDE_MODELS.OPUS,
				MAX_TOKENS.DRAFT,
				0.7, // Some creativity for engaging content
				[
					{
						role: "user",
						content: prompt,
					},
				],
			);
 
			console.log(
				"[generateDraft] AI response received, content blocks:",
				response.content?.length,
			);
 
			// Extract text content from response
			const content =
				response.content?.[0]?.type === "text" ? response.content[0].text : "";
 
			console.log(
				"[generateDraft] Extracted content length:",
				content.length,
				"characters",
			);
 
			return { content };
		} catch (err) {
			// Enhanced error logging with more details
			const errorDetails: { name: string; message: string } = {
				name: err instanceof Error ? err.name : "Unknown",
				message: err instanceof Error ? err.message : String(err),
			};
 
			console.error(
				"[generateDraft] AI draft generation failed:",
				errorDetails,
			);
			console.error("[generateDraft] Full error:", err);
 
			throw new Error(
				"AI service error: " +
					(err instanceof Error ? err.message : "Unknown error"),
			);
		}
	}
 
	async rewriteSection(
		params: RewritePromptParams,
	): Promise<RewriteSectionResponse> {
		try {
			const prompt = buildRewritePrompt(params);
 
			const response = await this.callClaudeAPI(
				CLAUDE_MODELS.OPUS,
				MAX_TOKENS.REWRITE,
				0.5, // Moderate creativity, stay closer to original
				[
					{
						role: "user",
						content: prompt,
					},
				],
			);
 
			const revisedContent =
				response.content?.[0]?.type === "text" ? response.content[0].text : "";
 
			return { revisedContent };
		} catch (err) {
			const safeError =
				err instanceof Error
					? { message: err.message, name: err.name }
					: { error: "Unknown error" };
			console.error("AI section rewrite failed:", safeError);
			throw new Error(
				`AI service error: ${err instanceof Error ? err.message : "Unknown"}`,
			);
		}
	}
 
	async generateMeta(params: MetaPromptParams): Promise<GenerateMetaResponse> {
		try {
			const prompt = buildMetaPrompt(params);
 
			const response = await this.callClaudeAPI(
				CLAUDE_MODELS.HAIKU, // Use faster model for structured output
				MAX_TOKENS.META,
				0, // Deterministic for consistent metadata
				[
					{
						role: "user",
						content: prompt,
					},
				],
			);
 
			const jsonText =
				response.content?.[0]?.type === "text"
					? response.content[0].text
					: "{}";
 
			try {
				// Extract JSON from potential markdown wrapper and parse
				const cleanedJSON = extractJSON(jsonText);
				const parsed = JSON.parse(cleanedJSON) as GenerateMetaResponse;
				return {
					title: parsed.title || "",
					meta_description: parsed.meta_description || "",
					suggested_slug: parsed.suggested_slug || "",
				};
			} catch (parseError) {
				/* v8 ignore start -- defensive: JSON.parse always throws Error subclass */
				const errMsg =
					parseError instanceof Error ? parseError.message : String(parseError);
				const errName =
					parseError instanceof Error ? parseError.name : "Unknown";
				/* v8 ignore stop */
				console.error(
					"Failed to parse meta generation response:",
					{ message: errMsg, name: errName },
					"Response preview:",
					jsonText.substring(0, 200),
				);
				throw new Error("Invalid JSON response from AI service");
			}
		} catch (err) {
			const safeError =
				err instanceof Error
					? { message: err.message, name: err.name }
					: { error: "Unknown error" };
			console.error("AI meta generation failed:", safeError);
			throw new Error(
				`AI service error: ${err instanceof Error ? err.message : "Unknown"}`,
			);
		}
	}
 
	async generateJSON<T>(
		prompt: string,
		options?: { model?: "opus" | "haiku"; maxTokens?: number; temperature?: number },
	): Promise<T> {
		const model = options?.model === "opus" ? CLAUDE_MODELS.OPUS : CLAUDE_MODELS.HAIKU;
		const response = await this.callClaudeAPI(
			model,
			options?.maxTokens ?? 2048,
			options?.temperature ?? 0,
			[{ role: "user", content: prompt }],
		);
		const text = response.content?.[0]?.type === "text" ? response.content[0].text : "{}";
		const cleaned = extractJSON(text);
		return JSON.parse(cleaned) as T;
	}
 
	async generateText(
		prompt: string,
		options?: { model?: "opus" | "haiku"; maxTokens?: number; temperature?: number },
	): Promise<string> {
		const model = options?.model === "opus" ? CLAUDE_MODELS.OPUS : CLAUDE_MODELS.HAIKU;
		const response = await this.callClaudeAPI(
			model,
			options?.maxTokens ?? 4096,
			options?.temperature ?? 0.7,
			[{ role: "user", content: prompt }],
		);
		return response.content?.[0]?.type === "text" ? response.content[0].text : "";
	}
 
	async suggestTopics(
		params: TopicSuggestionPromptParams,
	): Promise<SuggestTopicsResponse> {
		try {
			const prompt = buildTopicSuggestionPrompt(params);
 
			const response = await this.callClaudeAPI(
				CLAUDE_MODELS.HAIKU, // Use faster model for suggestions
				MAX_TOKENS.TOPICS,
				0.8, // Higher creativity for diverse topic ideas
				[
					{
						role: "user",
						content: prompt,
					},
				],
			);
 
			const jsonText =
				response.content?.[0]?.type === "text"
					? response.content[0].text
					: "[]";
 
			// Debug logging - log first 500 chars of raw response
			console.log(
				"[suggestTopics] Raw Claude response (first 500 chars):",
				jsonText.substring(0, 500),
			);
 
			try {
				// Extract JSON from potential markdown wrapper and parse
				const cleanedJSON = extractJSON(jsonText);
				console.log(
					"[suggestTopics] Cleaned JSON (first 500 chars):",
					cleanedJSON.substring(0, 500),
				);
				const suggestions = JSON.parse(cleanedJSON) as TopicSuggestion[];
				return { suggestions };
			} catch (parseError) {
				/* v8 ignore start -- defensive: JSON.parse always throws Error subclass */
				const errMsg =
					parseError instanceof Error ? parseError.message : String(parseError);
				const errName =
					parseError instanceof Error ? parseError.name : "Unknown";
				/* v8 ignore stop */
				console.error(
					"Failed to parse topic suggestions response:",
					{ message: errMsg, name: errName },
					"Response preview:",
					jsonText.substring(0, 200),
				);
				throw new Error("Invalid JSON response from AI service");
			}
		} catch (err) {
			const safeError =
				err instanceof Error
					? { message: err.message, name: err.name }
					: { error: "Unknown error" };
			console.error("AI topic suggestion failed:", safeError);
			throw new Error(
				`AI service error: ${err instanceof Error ? err.message : "Unknown"}`,
			);
		}
	}
}
 
/**
 * Mock AI service for testing and when AI is disabled
 */
class MockAIService implements AIService {
	async generateDraft(
		params: DraftPromptParams,
	): Promise<GenerateDraftResponse> {
		return {
			content: `# ${params.title}\n\n[Mock AI-generated content for blog about "${params.primaryKeyword}"]\n\nThis is a placeholder draft. AI features are currently disabled.`,
		};
	}
 
	async rewriteSection(
		_params: RewritePromptParams,
	): Promise<RewriteSectionResponse> {
		return {
			revisedContent:
				"[Mock AI-rewritten content]\n\nThis is a placeholder revision. AI features are currently disabled.",
		};
	}
 
	async generateMeta(params: MetaPromptParams): Promise<GenerateMetaResponse> {
		// Generate basic metadata from keyword
		const keyword = params.primaryKeyword;
		const slug = keyword.toLowerCase().replace(/\s+/g, "-");
 
		return {
			title: `${keyword.charAt(0).toUpperCase() + keyword.slice(1)} | Decor Rocket`,
			meta_description: `Learn about ${keyword} with expert tips and ideas from Decor Rocket.`,
			suggested_slug: slug,
		};
	}
 
	async suggestTopics(
		_params: TopicSuggestionPromptParams,
	): Promise<SuggestTopicsResponse> {
		return {
			suggestions: [
				{
					title: "Mock Blog Topic: Interior Design Ideas",
					blog_type: "general",
					primary_keyword: "interior design ideas",
					secondary_keywords: ["home decor", "design tips"],
					outline:
						"1. Introduction\n2. Main content\n3. Tips\n4. Conclusion\n5. CTA",
					seo_value:
						"Mock suggestion - AI features currently disabled for topic generation",
					pro_angle: "Feature pros with relevant expertise",
				},
			],
		};
	}
 
	async generateJSON<T>(_prompt: string): Promise<T> {
		return {} as T;
	}
 
	async generateText(_prompt: string): Promise<string> {
		return "[Mock AI text - AI features currently disabled]";
	}
}
 
/**
 * Factory function to create appropriate AI service based on environment
 * Returns mock service ONLY if AI features are explicitly disabled
 * Throws error if AI is enabled but API key is missing (fail fast)
 */
export function createAIService(env: CloudflareBindings): AIService {
	const aiEnabled = env.ENABLE_AI_FEATURES === "true";
	const hasApiKey = !!env.CLAUDE_API_KEY;
 
	console.log("[createAIService] AI enabled:", aiEnabled);
 
	// AI explicitly disabled - use mock service
	if (!aiEnabled) {
		console.warn(
			"[createAIService] AI features explicitly disabled, using mock service",
		);
		return new MockAIService();
	}
 
	// AI enabled but no API key - this is a configuration error, fail fast
	if (!hasApiKey) {
		console.error(
			"[createAIService] CLAUDE_API_KEY not configured but AI is enabled",
		);
		throw new Error(
			"AI features enabled but CLAUDE_API_KEY not configured. Please set CLAUDE_API_KEY environment variable or disable AI features.",
		);
	}
 
	// AI enabled with API key - use real service (guaranteed to exist after check above)
	console.log("[createAIService] Creating Claude AI service");
	const apiKey = env.CLAUDE_API_KEY;
	/* v8 ignore start -- defensive guard; apiKey validated above */
	if (!apiKey) {
		throw new Error("CLAUDE_API_KEY is required but not found");
	}
	/* v8 ignore stop */
	return new ClaudeAIService(apiKey, env);
}
 
/**
 * Check if AI features are enabled in the environment
 */
export function isAIEnabled(env: CloudflareBindings): boolean {
	return env.ENABLE_AI_FEATURES === "true" && !!env.CLAUDE_API_KEY;
}