CoolFace
Apppublic

admin08077/Githubgemini

sourceHugging Faceotherupdated 10mo agoView on Hugging Face
0likes
geminiService-Cgwdboli.js.map1 linesDownload Raw Back to assets
1{"version":3,"file":"geminiService-Cgwdboli.js","sources":["../../services/geminiService.ts"],"sourcesContent":["import { GoogleGenAI, Type, GenerateContentResponse, FunctionDeclaration, FunctionCall, Part } from \"@google/genai\";\nimport type { GeneratedFile, StructuredPrSummary, StructuredExplanation, ColorTheme } from '../types.ts';\nimport { logError } from './telemetryService.ts';\n\nconst API_KEY = process.env.GEMINI_API_KEY;\n\nif (!API_KEY) {\n  throw new Error(\"Gemini API key not found. Please set the GEMINI_API_KEY environment variable.\");\n}\nconst ai = new GoogleGenAI({ apiKey: API_KEY });\n\nconst sleep = (ms: number) => new Promise(resolve => setTimeout(resolve, ms));\n\n// --- Unified AI Helpers ---\n\nasync function* streamContent(prompt: string | { parts: any[] }, systemInstruction: string, temperature = 0.5) {\n    try {\n        const response = await ai.models.generateContentStream({\n            model: 'gemini-2.5-flash',\n            contents: prompt as any, // Cast to any to handle both string and parts object\n            config: { systemInstruction, temperature }\n        });\n\n        for await (const chunk of response) {\n            yield chunk.text;\n        }\n    } catch (error) {\n        console.error(\"Error streaming from AI model:\", error);\n        logError(error as Error, { prompt, systemInstruction });\n        if (error instanceof Error) {\n            yield `An error occurred while communicating with the AI model: ${error.message}`;\n        } else {\n            yield \"An unknown error occurred while generating the response.\";\n        }\n    }\n}\n\nasync function generateContent(prompt: string, systemInstruction: string, temperature = 0.5): Promise<string> {\n    try {\n        const response = await ai.models.generateContent({\n            model: 'gemini-2.5-flash',\n            contents: prompt,\n            config: { systemInstruction, temperature }\n        });\n        return response.text;\n    } catch (error) {\n         console.error(\"Error generating content from AI model:\", error);\n        logError(error as Error, { prompt, systemInstruction });\n        throw error;\n    }\n}\n\n\nasync function generateJson<T>(prompt: string, systemInstruction: string, schema: any, temperature = 0.2): Promise<T> {\n    try {\n        const response = await ai.models.generateContent({\n            model: \"gemini-2.5-flash\",\n            contents: prompt,\n            config: {\n                systemInstruction,\n                responseMimeType: \"application/json\",\n                responseSchema: schema,\n                temperature,\n            }\n        });\n        return JSON.parse(response.text.trim());\n    } catch (error) {\n        console.error(\"Error generating JSON from AI model:\", error);\n        logError(error as Error, { prompt, systemInstruction });\n        throw error;\n    }\n}\n\n\n// --- Unified Feature Functions (Streaming) ---\n\nexport const explainCodeStream = (code: string) => streamContent(\n    `Please explain the following code snippet:\\n\\n\\`\\`\\`\\n${code}\\n\\`\\`\\``,\n    \"You are an expert software engineer providing a clear, concise explanation of code.\"\n);\n\nexport const generateRegExStream = (description: string) => streamContent(\n    `Generate a single valid JavaScript regex literal (e.g., /abc/gi) for the following description. Respond with ONLY the regex literal and nothing else: \"${description}\"`,\n    \"You are an expert in regular expressions. You only output valid JavaScript regex literals.\",\n    0.7\n);\n\nexport const generateCommitMessageStream = (diff: string) => streamContent(\n    `Generate a conventional commit message for the following context of new files being added:\\n\\n${diff}`,\n    \"You are an expert programmer who writes excellent, conventional commit messages. The response should be only the commit message text.\",\n    0.8\n);\n\nexport const generateUnitTestsStream = (code: string) => streamContent(\n    `Generate Vitest unit tests for this React component code:\\n\\n\\`\\`\\`tsx\\n${code}\\n\\`\\`\\``,\n    \"You are a software quality engineer specializing in writing comprehensive and clear unit tests using Vitest and React Testing Library.\",\n    0.6\n);\n\nexport const formatCodeStream = (code: string) => streamContent(\n    `Format this code:\\n\\n\\`\\`\\`javascript\\n${code}\\n\\`\\`\\``,\n    \"You are a code formatter. Your only purpose is to format code. Respond with only the formatted code, enclosed in a single markdown block.\",\n    0.2\n);\n\nexport const generateComponentFromImageStream = (base64Image: string) => streamContent(\n    {\n        parts: [\n            { text: \"Generate a single-file React component using Tailwind CSS that looks like this image. Respond with only the code in a markdown block.\" },\n            { inlineData: { mimeType: 'image/png', data: base64Image } }\n        ]\n    },\n    \"You are an expert frontend developer specializing in React and Tailwind CSS. You create clean, functional components from screenshots.\"\n);\n\nexport const transcribeAudioToCodeStream = (base64Audio: string, mimeType: string) => streamContent(\n    {\n        parts: [\n            { text: \"Transcribe my speech into a code snippet. If I describe a function or component, write it out.\" },\n            { inlineData: { mimeType, data: base64Audio } }\n        ]\n    },\n    \"You are an expert programmer. You listen to a user's voice and transcribe their ideas into code.\"\n);\n\nexport const transferCodeStyleStream = (args: { code: string, styleGuide: string }) => streamContent(\n    `Rewrite the following code to match the provided style guide.\\n\\nStyle Guide:\\n${args.styleGuide}\\n\\nCode to rewrite:\\n\\`\\`\\`\\n${args.code}\\n\\`\\`\\``,\n    \"You are an AI assistant that rewrites code to match a specific style guide. Respond with only the rewritten code in a markdown block.\",\n    0.3\n);\n\nexport const generateCodingChallengeStream = (_: any) => streamContent(\n    `Generate a new, interesting coding challenge suitable for an intermediate developer. Include a clear problem description, one or two examples, and any constraints. Format it in markdown.`,\n    \"You are an AI that creates unique and interesting coding challenges for software developers.\",\n    0.9\n);\n\nexport const reviewCodeStream = (code: string) => streamContent(\n    `Please perform a detailed code review on the following code snippet. Identify potential bugs, suggest improvements for readability and performance, and point out any anti-patterns. Structure your feedback with clear headings.\\n\\n\\`\\`\\`\\n${code}\\n\\`\\`\\``,\n    \"You are a senior software engineer performing a code review. You are meticulous, helpful, and provide constructive feedback.\",\n    0.6\n);\n\nexport const generateChangelogFromLogStream = (log: string) => streamContent(\n    `Analyze this git log and create a changelog:\\n\\n\\`\\`\\`\\n${log}\\n\\`\\`\\``,\n    \"You are a git expert and project manager. Analyze the provided git log and generate a clean, categorized changelog in Markdown format. Group changes under 'Features' and 'Fixes'.\",\n    0.6\n);\n\nexport const enhanceSnippetStream = (code: string) => streamContent(\n    `Enhance this code snippet. Add comments, improve variable names, and refactor for clarity or performance if possible.\\n\\n\\`\\`\\`\\n${code}\\n\\`\\`\\``,\n    \"You are a senior software engineer who excels at improving code. Respond with only the enhanced code in a markdown block.\",\n    0.5\n);\n\nexport const summarizeNotesStream = (notes: string) => streamContent(\n    `Summarize these developer notes into a bulleted list of key points and action items:\\n\\n${notes}`,\n    \"You are a productivity assistant who is an expert at summarizing technical notes.\",\n    0.7\n);\n\nexport const migrateCodeStream = (code: string, from: string, to: string) => streamContent(\n    `Translate this ${from} code to ${to}. Respond with only the translated code in a markdown block.\\n\\n\\`\\`\\`\\n${code}\\n\\`\\`\\``,\n    `You are an expert polyglot programmer who specializes in migrating code between languages and frameworks.`,\n    0.4\n);\n\nexport const analyzeConcurrencyStream = (code: string) => streamContent(\n    `Analyze this JavaScript code for potential concurrency issues, especially related to Web Workers. Identify race conditions, deadlocks, or inefficient data passing.\\n\\n\\`\\`\\`javascript\\n${code}\\n\\`\\`\\``,\n    \"You are an expert in JavaScript concurrency, web workers, and multi-threaded programming concepts.\",\n    0.6\n);\n\nexport const debugErrorStream = (error: Error) => streamContent(\n    `I encountered an error in my React application. Here are the details:\n    \n    Message: ${error.message}\n    \n    Stack Trace:\n    ${error.stack}\n    \n    Please analyze this error. Provide a brief explanation of the likely cause, followed by a bulleted list of potential solutions or debugging steps. Structure your response in clear, concise markdown.`,\n    \"You are an expert software engineer specializing in debugging React applications. You provide clear, actionable advice to help developers solve errors.\"\n);\n\nexport const convertJsonToXbrlStream = (json: string) => streamContent(\n    `Convert the following JSON to a simplified, XBRL-like XML format. Use meaningful tags based on the JSON keys. The root element should be <xbrl>. Do not include XML declarations or namespaces.\\n\\nJSON:\\n${json}`,\n    \"You are an expert in data formats who converts JSON to clean, XBRL-like XML.\"\n);\n\n// --- Simple Generate Content ---\nexport const generateUnitTests = (code: string): Promise<string> => generateContent(\n    `Generate Vitest unit tests for this React component code:\\n\\n\\`\\`\\`tsx\\n${code}\\n\\`\\`\\``,\n    \"You are a software quality engineer specializing in writing unit tests. Respond with only the test code in a markdown block.\",\n    0.6\n);\n\nexport const generateCommitMessage = (diff: string): Promise<string> => generateContent(\n    `Generate a commit message for the following context of new files being added:\\n\\n${diff}`,\n    \"You are an expert programmer who writes excellent, conventional commit messages.\",\n    0.8\n);\n\n\n// --- STRUCTURED JSON ---\n\nexport const explainCodeStructured = async (code: string): Promise<StructuredExplanation> => {\n    const systemInstruction = \"You are an expert software engineer providing a structured analysis of a code snippet.\";\n    const prompt = `Analyze this code: \\n\\n\\`\\`\\`\\n${code}\\n\\`\\`\\``;\n    const schema = {\n        type: Type.OBJECT,\n        properties: {\n            summary: { type: Type.STRING, description: \"A high-level summary of what the code does.\" },\n            lineByLine: {\n                type: Type.ARRAY,\n                description: \"A line-by-line or block-by-block explanation.\",\n                items: {\n                    type: Type.OBJECT,\n                    properties: {\n                        lines: { type: Type.STRING, description: \"The line range, e.g., '1-5'.\" },\n                        explanation: { type: Type.STRING, description: \"The explanation for that line range.\" }\n                    },\n                    required: [\"lines\", \"explanation\"]\n                }\n            },\n            complexity: {\n                type: Type.OBJECT,\n                description: \"Big O notation for time and space complexity.\",\n                properties: {\n                    time: { type: Type.STRING, description: \"e.g., O(n^2)\" },\n                    space: { type: Type.STRING, description: \"e.g., O(1)\" }\n                },\n                required: [\"time\", \"space\"]\n            },\n            suggestions: {\n                type: Type.ARRAY,\n                description: \"Suggestions for improvement or alternatives.\",\n                items: { type: Type.STRING }\n            }\n        },\n        required: [\"summary\", \"lineByLine\", \"complexity\", \"suggestions\"]\n    };\n\n    return generateJson(prompt, systemInstruction, schema);\n}\n\nexport const generateThemeFromDescription = async (description: string): Promise<ColorTheme> => {\n    const systemInstruction = \"You are a UI/UX design expert specializing in color theory. Generate a color theme based on the user's description. Provide hex codes for each color.\";\n    const prompt = `Generate a color theme for: \"${description}\"`;\n    const schema = {\n        type: Type.OBJECT,\n        properties: {\n            primary: { type: Type.STRING, description: \"The primary accent color.\" },\n            background: { type: Type.STRING, description: \"The main background color.\" },\n            surface: { type: Type.STRING, description: \"The color for card backgrounds or surfaces.\" },\n            textPrimary: { type: Type.STRING, description: \"The color for primary text.\" },\n            textSecondary: { type: Type.STRING, description: \"The color for secondary or muted text.\" }\n        },\n        required: [\"primary\", \"background\", \"surface\", \"textPrimary\", \"textSecondary\"]\n    };\n    return generateJson(prompt, systemInstruction, schema);\n};\n\nexport const generatePrSummaryStructured = (diff: string): Promise<StructuredPrSummary> => {\n    const systemInstruction = \"You are an expert programmer who writes excellent PR summaries.\";\n    const prompt = `Generate a PR summary for the following diff:\\n\\n\\`\\`\\`diff\\n${diff}\\n\\`\\`\\``;\n    const schema = {\n        type: Type.OBJECT,\n        properties: {\n            title: { type: Type.STRING, description: \"A concise, conventional PR title.\" },\n            summary: { type: Type.STRING, description: \"A one or two sentence summary of the changes.\" },\n            changes: { type: Type.ARRAY, items: { type: Type.STRING }, description: \"A bulleted list of the most important changes.\" }\n        },\n        required: [\"title\", \"summary\", \"changes\"]\n    };\n    return generateJson(prompt, systemInstruction, schema);\n};\n\nexport const generateFeature = (prompt: string): Promise<GeneratedFile[]> => {\n    const systemInstruction = \"You are an AI that generates complete, production-ready React components. Create all necessary files (component, styles, etc.).\";\n    const userPrompt = `Generate the files for the following feature request: \"${prompt}\". Make sure to include a .tsx component file.`;\n    const schema = {\n        type: Type.ARRAY,\n        items: {\n            type: Type.OBJECT,\n            properties: {\n                filePath: { type: Type.STRING, description: \"The full path of the file, e.g., 'src/components/MyComponent.tsx'.\" },\n                content: { type: Type.STRING, description: \"The complete code content of the file.\" },\n                description: { type: Type.STRING, description: \"A brief description of what this file does.\" }\n            },\n            required: [\"filePath\", \"content\", \"description\"]\n        }\n    };\n    return generateJson(userPrompt, systemInstruction, schema);\n};\n\nexport interface CronParts {\n    minute: string;\n    hour: string;\n    dayOfMonth: string;\n    month: string;\n    dayOfWeek: string;\n}\nexport const generateCronFromDescription = (description: string): Promise<CronParts> => {\n    const systemInstruction = \"You are an expert in cron expressions. Convert the user's description into a valid cron expression parts.\";\n    const prompt = `Convert this schedule to a cron expression: \"${description}\"`;\n    const schema = {\n        type: Type.OBJECT,\n        properties: {\n            minute: { type: Type.STRING },\n            hour: { type: Type.STRING },\n            dayOfMonth: { type: Type.STRING },\n            month: { type: Type.STRING },\n            dayOfWeek: { type: Type.STRING }\n        },\n        required: [\"minute\", \"hour\", \"dayOfMonth\", \"month\", \"dayOfWeek\"]\n    };\n    return generateJson(prompt, systemInstruction, schema);\n};\n\nexport const generateColorPalette = (baseColor: string): Promise<{ colors: string[] }> => {\n    const systemInstruction = \"You are a color theory expert. Generate a 6-color palette based on the given base color.\";\n    const prompt = `Generate a harmonious 6-color palette based on the color ${baseColor}.`;\n    const schema = {\n        type: Type.OBJECT,\n        properties: {\n            colors: { type: Type.ARRAY, items: { type: Type.STRING } }\n        },\n        required: [\"colors\"]\n    };\n    return generateJson(prompt, systemInstruction, schema);\n};\n\n// --- FUNCTION CALLING ---\nexport interface CommandResponse {\n    text: string;\n    functionCalls?: { name: string; args: any; }[];\n}\n\nexport const getInferenceFunction = async (prompt: string, functionDeclarations: FunctionDeclaration[], knowledgeBase: string): Promise<CommandResponse> => {\n    try {\n        const systemInstruction = `You are a helpful assistant for a developer tool. The user will ask you to perform a task.\n        Based on your knowledge base of available tools, you must decide which function to call to satisfy the user's request.\n        If no specific tool seems appropriate, you can respond with text.\n        \n        Knowledge Base of Available Tools:\n        ${knowledgeBase}`;\n\n        const response: GenerateContentResponse = await ai.models.generateContent({\n            model: \"gemini-2.5-flash\",\n            contents: prompt,\n            config: {\n                systemInstruction,\n                tools: [{ functionDeclarations }],\n            }\n        });\n\n        const functionCalls: { name: string, args: any }[] = [];\n        const parts: Part[] = response.candidates?.[0]?.content?.parts ?? [];\n        \n        for (const part of parts) {\n            if (part.functionCall) {\n                functionCalls.push({\n                    name: part.functionCall.name,\n                    args: part.functionCall.args,\n                });\n            }\n        }\n        \n        return {\n            text: response.text,\n            functionCalls: functionCalls.length > 0 ? functionCalls : undefined,\n        };\n\n    } catch (error) {\n        logError(error as Error, { prompt });\n        throw error;\n    }\n};\n\n\n/**\n * Generates an image from a text prompt using the Gemini API via fetch.\n * Includes a retry mechanism with exponential backoff for improved reliability.\n * @param prompt A text description of the image to generate.\n * @returns A promise that resolves with the data URL of the generated image.\n */\nexport const generateImage = async (prompt: string): Promise<string> => {\n    const API_URL = \"https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash-preview-image-generation:generateContent\";\n    const API_KEY = process.env.GEMINI_API_KEY;\n\n    if (!API_KEY) {\n        throw new Error(\"Gemini API key not found.\");\n    }\n\n    const body = {\n        \"contents\": [{\n            \"parts\": [\n                { \"text\": prompt }\n            ]\n        }],\n        \"generationConfig\": { \"responseModalities\": [\"TEXT\", \"IMAGE\"] }\n    };\n\n    const MAX_RETRIES = 3;\n    let lastError: Error | null = null;\n\n    for (let i = 0; i < MAX_RETRIES; i++) {\n        try {\n            const response = await fetch(API_URL, {\n                method: 'POST',\n                headers: {\n                    'x-goog-api-key': API_KEY,\n                    'Content-Type': 'application/json',\n                },\n                body: JSON.stringify(body),\n            });\n\n            if (!response.ok) {\n                const errorText = await response.text();\n                throw new Error(`API request failed with status ${response.status}: ${errorText}`);\n            }\n\n            const data = await response.json();\n\n            const imagePart = data.candidates?.[0]?.content?.parts?.find(\n                (part: any) => part.inlineData && part.inlineData.mimeType.startsWith('image/')\n            );\n\n            if (imagePart && imagePart.inlineData.data) {\n                const base64Image = imagePart.inlineData.data;\n                const mimeType = imagePart.inlineData.mimeType;\n                return `data:${mimeType};base64,${base64Image}`;\n            }\n\n            const textResponse = data.candidates?.[0]?.content?.parts?.find((p: any) => p.text)?.text;\n            if (textResponse) {\n                 throw new Error(`API returned text instead of an image: ${textResponse}`);\n            }\n            throw new Error(\"API response did not contain valid image data.\");\n\n        } catch (error) {\n            lastError = error instanceof Error ? error : new Error(String(error));\n            logError(lastError, { context: 'generateImageFetch', attempt: i + 1, prompt });\n            console.warn(`Attempt ${i + 1} failed. Retrying in ${Math.pow(2, i)}s...`);\n            if (i < MAX_RETRIES - 1) {\n                await sleep(1000 * Math.pow(2, i)); // Exponential backoff: 1s, 2s\n            }\n        }\n    }\n\n    throw new Error(`Failed to generate image after ${MAX_RETRIES} attempts. The service may be busy or the prompt may have been blocked. Please try again with a different prompt. Last error: ${lastError?.message}`);\n};"],"names":["API_KEY","ai","GoogleGenAI","streamContent","prompt","systemInstruction","temperature","response","chunk","error","logError","generateJson","schema","generateRegExStream","description","generateComponentFromImageStream","base64Image","generateChangelogFromLogStream","log","enhanceSnippetStream","code","analyzeConcurrencyStream","convertJsonToXbrlStream","json","generateThemeFromDescription","Type"],"mappings":"yFAIA,MAAMA,EAAU,0CAKVC,EAAK,IAAIC,EAAY,CAAE,OAAQF,EAAS,EAM9C,eAAgBG,EAAcC,EAAmCC,EAA2BC,EAAc,GAAK,CAC3G,GAAI,CACA,MAAMC,EAAW,MAAMN,EAAG,OAAO,sBAAsB,CACnD,MAAO,mBACP,SAAUG,EACV,OAAQ,CAAE,kBAAAC,EAAmB,YAAAC,CAAA,CAAY,CAC5C,EAED,gBAAiBE,KAASD,EACtB,MAAMC,EAAM,IAEpB,OAASC,EAAO,CACZ,QAAQ,MAAM,iCAAkCA,CAAK,EACrDC,EAASD,EAAgB,CAAE,OAAAL,EAAQ,kBAAAC,CAAA,CAAmB,EAClDI,aAAiB,MACjB,KAAM,4DAA4DA,EAAM,OAAO,GAE/E,KAAM,0DAEd,CACJ,CAkBA,eAAeE,EAAgBP,EAAgBC,EAA2BO,EAAaN,EAAc,GAAiB,CAClH,GAAI,CACA,MAAMC,EAAW,MAAMN,EAAG,OAAO,gBAAgB,CAC7C,MAAO,mBACP,SAAUG,EACV,OAAQ,CACJ,kBAAAC,EACA,iBAAkB,mBAClB,eAAgBO,EAChB,YAAAN,CAAA,CACJ,CACH,EACD,OAAO,KAAK,MAAMC,EAAS,KAAK,MAAM,CAC1C,OAASE,EAAO,CACZ,cAAQ,MAAM,uCAAwCA,CAAK,EAC3DC,EAASD,EAAgB,CAAE,OAAAL,EAAQ,kBAAAC,CAAA,CAAmB,EAChDI,CACV,CACJ,CAUO,MAAMI,EAAuBC,GAAwBX,EACxD,0JAA0JW,CAAW,IACrK,6FACA,EACJ,EAoBaC,EAAoCC,GAAwBb,EACrE,CACI,MAAO,CACH,CAAE,KAAM,uIAAA,EACR,CAAE,WAAY,CAAE,SAAU,YAAa,KAAMa,EAAY,CAAE,CAC/D,EAEJ,wIACJ,EA8BaC,EAAkCC,GAAgBf,EAC3D;AAAA;AAAA;AAAA,EAA2De,CAAG;AAAA,QAC9D,qLACA,EACJ,EAEaC,EAAwBC,GAAiBjB,EAClD;AAAA;AAAA;AAAA,EAAoIiB,CAAI;AAAA,QACxI,4HACA,EACJ,EAcaC,EAA4BD,GAAiBjB,EACtD;AAAA;AAAA;AAAA,EAA4LiB,CAAI;AAAA,QAChM,qGACA,EACJ,EAcaE,EAA2BC,GAAiBpB,EACrD;AAAA;AAAA;AAAA,EAA6MoB,CAAI,GACjN,8EACJ,EA0DaC,EAA+B,MAAOV,GAA6C,CAC5F,MAAMT,EAAoB,wJACpBD,EAAS,gCAAgCU,CAAW,IACpDF,EAAS,CACX,KAAMa,EAAK,OACX,WAAY,CACR,QAAS,CAAE,KAAMA,EAAK,OAAQ,YAAa,2BAAA,EAC3C,WAAY,CAAE,KAAMA,EAAK,OAAQ,YAAa,4BAAA,EAC9C,QAAS,CAAE,KAAMA,EAAK,OAAQ,YAAa,6CAAA,EAC3C,YAAa,CAAE,KAAMA,EAAK,OAAQ,YAAa,6BAAA,EAC/C,cAAe,CAAE,KAAMA,EAAK,OAAQ,YAAa,wCAAA,CAAyC,EAE9F,SAAU,CAAC,UAAW,aAAc,UAAW,cAAe,eAAe,CAAA,EAEjF,OAAOd,EAAaP,EAAQC,EAAmBO,CAAM,CACzD"}