Showing preview only (274K chars total). Download the full file or copy to clipboard to get everything.
Repository: qyjoy/AI-worker
Branch: main
Commit: e0d0eeb8eb25
Files: 23
Total size: 256.0 KB
Directory structure:
gitextract_dmkitj7p/
├── .github/
│ └── ISSUE_TEMPLATE/
│ ├── cn.yaml
│ ├── config.yml
│ ├── en.yaml
│ └── ru.yaml
├── All in one Portable(outdated)/
│ └── AI-WorkerOldRelease.js
├── LICENSE
├── README.md
├── V3(stable)/
│ ├── api-handler.js
│ ├── html-rendererv3.js
│ ├── request-handler.js
│ ├── utils.js
│ └── worker.js
├── V4 EX(For mobile support Expand)/
│ ├── api-handler.js
│ ├── html-renderer.js
│ ├── request-handler.js
│ ├── utils.js
│ └── worker.js
├── V4(latest)/
│ ├── api-handler.js
│ ├── html-renderer.js
│ ├── request-handler.js
│ ├── utils.js
│ └── worker.js
└── autoRenice.sh
================================================
FILE CONTENTS
================================================
================================================
FILE: .github/ISSUE_TEMPLATE/cn.yaml
================================================
name: ⚠功能性問題回報
description: 回報一個明確的功能性錯誤,例如按鈕無效或邏輯錯誤
title: "標題:請簡要描述問題"
labels: [enhancement, question, documentation, invalid, help wanted, functional]
body:
- type: markdown
attributes:
value: |
感謝你的提交!請確認你回報的是一個 **功能性問題(functional problem)**,而不是效能、體驗或個人意見等非功能性問題。
- type: dropdown
id: issue-type
attributes:
label: 問題類型
description: 請選擇你回報的問題類型
options:
- 功能性(F:Functional)問題(功能邏輯錯誤、按鈕無作用等)
- 非功能性(NF:Non-Functional)問題(UI不佳、速度慢、體驗建議等)❌請勿在此提交
default: 0
validations:
required: true
- type: input
id: environment
attributes:
label: 運行環境
description: 請提供你的瀏覽器、作業系統、版本等資訊
placeholder: 例如:Chrome 123 / macOS 14.4
validations:
required: true
- type: textarea
id: reproduce-steps
attributes:
label: 重現步驟
description: 請詳述重現問題的步驟
placeholder: |
1. 打開頁面
2. 點擊按鈕X
3. 發生了問題Y
validations:
required: true
- type: textarea
id: expected-behavior
attributes:
label: 預期行為(至少25字,太短可能會被AI自動退回)
description: 描述你原本期望看到的結果
validations:
required: true
- type: textarea
id: actual-behavior
attributes:
label: 實際行為(提供截圖,至少25字,太短可能會被AI自動退回)
description: 描述實際出現的狀況(提供截圖)
validations:
required: true
- type: checkboxes
id: confirmations
attributes:
label: 提交確認(如果你確定此issue為BUG,可在標籤label勾選加上'BUG')
options:
- label: 我確認:這是一個功能性問題,而不是建議或非功能性問題
required: true
- label: 我承認並同意:本issue的分類與處理(如Close、標記為invalid)最終解釋權歸本項目貢獻者與維護者所有
required: true
================================================
FILE: .github/ISSUE_TEMPLATE/config.yml
================================================
blank_issues_enabled: false
contact_links:
- name: ⛔ [RU]Пожалуйста, не отправляйте нефункциональные проблемы здесь
url: https://github.com/qyjoy/Gemini-CFworker/discussions
about: Для отзывов и предложений по производительности используйте Discussions
- name: ⛔ [CN]請勿在此提交非功能性問題
url: https://github.com/qyjoy/Gemini-CFworker/discussions
about: 體驗問題、效能建議請移步 Discussions 區域
- name: ⛔ [EN]You are not allowed to report non-functional issues here
url: https://github.com/qyjoy/Gemini-CFworker/discussions
about: For feedback or performance suggestions, use Discussions
================================================
FILE: .github/ISSUE_TEMPLATE/en.yaml
================================================
name: ⚠Functional Issue Report
description: Report a clear functional error, such as a button not working or a logic bug
title: "Title: Please briefly describe the issue"
labels: [enhancement, question, documentation, invalid, help wanted, functional]
body:
- type: markdown
attributes:
value: |
Thank you for your submission! Please make sure you're reporting a **functional issue**, not a performance concern, UI feedback, or personal suggestion.
- type: dropdown
id: issue-type
attributes:
label: Type of Issue
description: Please select the type of problem you're reporting
options:
- Functional (F): Functional error such as logic bugs or non-working buttons
- Non-Functional (NF): UI/UX issues, slowness, suggestions etc. ❌ Please do NOT submit here
default: 0
validations:
required: true
- type: input
id: environment
attributes:
label: Runtime Environment
description: Provide your browser, OS, and version
placeholder: e.g. Chrome 123 / macOS 14.4
validations:
required: true
- type: textarea
id: reproduce-steps
attributes:
label: Steps to Reproduce
description: Provide detailed steps to reproduce the issue
placeholder: |
1. Open the page
2. Click button X
3. Problem Y occurs
validations:
required: true
- type: textarea
id: expected-behavior
attributes:
label: Expected Behavior (at least 50 EN characters, too short may be auto-rejected by AI)
description: Describe what you expected to happen
validations:
required: true
- type: textarea
id: actual-behavior
attributes:
label: Actual Behavior (attach screenshot, at least 50 EN characters, too short may be auto-rejected by AI)
description: Describe what actually happened (attach screenshot)
validations:
required: true
- type: checkboxes
id: confirmations
attributes:
label: Submission Confirmation (If you’re sure this is a bug, you can add the 'BUG' label)
options:
- label: I confirm this is a functional issue, not a suggestion or non-functional feedback
required: true
- label: I acknowledge and agree that the final interpretation and handling (e.g. Close, mark as invalid) of this issue lies with the project contributors and maintainers
required: true
================================================
FILE: .github/ISSUE_TEMPLATE/ru.yaml
================================================
name: ⚠Сообщение о функциональной проблеме
description: Сообщите о чёткой функциональной ошибке, например, неработающей кнопке или сбое в логике
title: "Заголовок: кратко опишите проблему"
labels: [enhancement, question, documentation, invalid, help wanted, functional]
body:
- type: markdown
attributes:
value: |
Спасибо за ваше сообщение! Убедитесь, что вы сообщаете именно о **функциональной проблеме**, а не об общей производительности, удобстве или субъективных предложениях.
- type: dropdown
id: issue-type
attributes:
label: Тип проблемы
description: Пожалуйста, выберите тип ошибки
options:
- "Функциональная (F): Ошибки логики, неработающие кнопки и т.п."
- "Нефункциональная (NF): UI-проблемы, медленная работа, предложения и т.д. ❌ Не отправлять здесь"
default: 0
validations:
required: true
- type: input
id: environment
attributes:
label: Окружение
description: Укажите ваш браузер, операционную систему и версию
placeholder: "Chrome 123 / macOS 14.4"
validations:
required: true
- type: textarea
id: reproduce-steps
attributes:
label: Шаги для воспроизведения
placeholder: |
1. Откройте страницу
2. Нажмите кнопку X
3. Произошла ошибка Y
validations:
required: true
- type: textarea
id: expected-behavior
attributes:
label: Ожидаемое поведение (минимум 30 символов)
validations:
required: true
maxLength: 200
- type: textarea
id: actual-behavior
attributes:
label: Фактическое поведение (с приложением скриншота)
validations:
required: true
- type: checkboxes
id: confirmations
attributes:
label: Подтверждение отправки
options:
- label: "Я подтверждаю, что это функциональная проблема"
required: true
- label: "Я согласен с политикой обработки issue"
required: true
================================================
FILE: All in one Portable(outdated)/AI-WorkerOldRelease.js
================================================
// Helper Function for CORS Headers
function corsHeaders()
{return {
"Access-Control-Allow-Origin": "*", // WARNING: Restrict this in production
"Access-Control-Allow-Methods": "GET, POST, OPTIONS",
"Access-Control-Allow-Headers": "Content-Type", // Add any other headers your client might send
}; }
function renderHTML() {
return `
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>輕音Joy-AI公益站</title>
<link rel="icon" href="https://www.cloudflare.com/favicon.ico" type="image/x-icon">
<script src="https://cdn.tailwindcss.com"></script>
<style>
.ai-message strong::before {
content: "";
display: inline-block;
width: 20px;
height: 20px;
background-image: url('https://www.gstatic.com/lamda/images/sparkle_resting_v2_1ff6f6a71f2d298b1a31.gif');
background-size: contain;
background-repeat: no-repeat;
margin-right: 8px;
vertical-align: middle;
}
.text-3xl{background:linear-gradient(90deg,red,orange,yellow,green,blue,purple,red);-webkit-background-clip:text;background-clip:text;color:transparent;background-size:500% auto;animation:rainbow 10s linear infinite}@keyframes rainbow{0%{background-position:0}100%{background-position:500%}}
/* 恢复深度思考中文字动画 */
@keyframes textGlow{0%{text-shadow:0 0 10px rgba(255,255,255,.8),0 0 20px rgba(100,200,255,.6);transform:scale(1)}50%{text-shadow:0 0 30px rgba(100,150,255,.9),0 0 50px rgba(200,100,255,.8),0 0 70px rgba(255,0,200,.6);transform:scale(1.05)}100%{text-shadow:0 0 10px rgba(255,255,255,.8),0 0 20px rgba(100,200,255,.6);transform:scale(1)}}
.thinking{animation:textGlow 1.5s ease-in-out infinite;color:#a78bfa!important;font:italic bold 1.2em sans-serif}
@keyframes icon2DRotate {
0% { opacity: 0; transform: scale(0) rotateY(0deg); }
10% { opacity: 1; transform: scale(3) rotateY(0deg); }
50% { transform: scale(3) rotateY(180deg); }
90% { transform: scale(3) rotateY(350deg); }
100% { opacity: 0; transform: scale(0) rotateY(360deg); }
}
.thinking-icon {
position: absolute; top: 30%; left: 50%;
width: 80px; height: 80px; margin: -40px 0 0 -40px;
pointer-events: none;
animation: icon2DRotate 6s ease-in-out forwards;
transform-origin: center center;
transform-style: preserve-3d;
filter: drop-shadow(0 0 25px #dba0ff) brightness(1.5) saturate(1.8);
z-index: 999;
}
body {
background: url('https://www.sensecore.cn/upload/20230330/crjfafitbja7qufwrt.jpg') no-repeat center center fixed;
background-size: cover;
}
/* 添加透明背景设置https://www.bleepstatic.com/content/hl-images/2023/11/02/cloudflare.jpg https://dlink.host/sharepoint/aHR0cHM6Ly80YzJ4ZHQtbXkuc2hhcmVwb2ludC5jb20vOmk6L2cvcGVyc29uYWwvYWRtaW5fNGMyeGR0X29ubWljcm9zb2Z0X2NvbS9FUms0ZTloVldPQk5reU0zLWxaSEwyQUJjRm1DNUltUUdwVGpCcXNoLVNBTzNBP2U9ZllDVkp0.png*/
.w-full.max-w-6xl {
background-color: rgba(31, 41, 55, 0.85)!important;
backdrop-filter: blur(4px); /* 可选:背景模糊效果 */
}
/* 聊天消息透明 */
#chat > div {
background-color: rgba(30, 64, 175, 0.8); /* 用户消息 */
}
.ai-message {background-color: rgba(55, 65, 81, 0.8); /* AI消息 */}
/* 输入框透明 */
background-color: rgba(55, 65, 81, 0.5)!important;
backdrop-filter: blur(2px);
#sendBtn, select { background-color: rgba(55, 65, 81, 0.5)!important; }
#sendBtn:hover { background-color: rgba(29, 78, 216, 0.6)!important;}
#chat-container { max-height: 60vh; overflow-y: auto; }
#chat > div { margin-bottom: 1rem; padding: 0.75rem; border-radius: 0.5rem; max-width: 90%; word-break: break-word; line-height: 1.6; }
.user-message { background-color: #1e40af; color: white; align-self: flex-end; margin-left: 10%; }
.ai-message { background-color: #374151; color: white; align-self: flex-start; margin-right: 10%; white-space: pre-wrap; }
.ai-message img { display: block; max-width: 100%; max-height: 400px; height: auto; margin-top: 0.75rem; border-radius: 0.375rem; background-color: #4b5563; }
.ai-message strong, .user-message strong { display: block; margin-bottom: 0.25rem; font-weight: bold; color: #9ca3af; }
.error-message { background-color: #b91c1c; color: white; }
.loader { border: 4px solid #f3f3f3; border-top: 4px solid #3498db; border-radius: 50%; width: 20px; height: 20px; animation: spin 1s linear infinite; display: inline-block; margin-left: 8px; }
@keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }
textarea { scrollbar-width: thin; scrollbar-color: #4b5563 #374151; }
</style>
</head>
<body class="bg-gray-900 text-gray-100 min-h-screen flex flex-col items-center p-4 font-sans">
<h1 class="text-3xl font-bold my-6 text-center">Ultra Gemini ☁ Cloudflare 輕音Joy-AI公益站</h1>
<a href="https://qyjoy.vip" target="_blank" class="text-center block font-bold cursor-pointer mb-6 animate-breathe" style="text-shadow:0 0 8px rgba(0,255,255,0.7);">抖音 | Bilibili | Youtube | 小红书 | 公众号: 輕音Joy</a>
<style>@keyframes breathe{0%{color:white;text-shadow:0 0 8px rgba(255,255,255,0.7);}50%{color:#22d3ee;text-shadow:0 0 12px rgba(34,211,238,0.9);}100%{color:white;text-shadow:0 0 8px rgba(255,255,255,0.7);}}.animate-breathe{animation:breathe 3s ease-in-out infinite;}</style>
<div class="w-full max-w-6xl bg-gray-800 shadow-lg rounded-lg p-6">
<div class="mb-4">
<label for="model" class="block mb-2 text-sm font-medium text-gray-300">选择模型:</label>
<select id="model" class="w-full p-2.5 rounded bg-gray-700 border border-gray-600/50 text-white focus:ring-blue-500 focus:border-blue-500" style="background:rgba(55,65,81,0)!important;backdrop-filter:blur(4px)">
<option value="gemini-2.5-flash-preview-04-17">Gemini 2.5 Pro Preview </option>
</select>
</div>
<div class="mb-4">
<label for="prompt" class="block mb-2 text-sm font-medium text-gray-300">输入你的内容或画面描述:</label>
<textarea id="prompt" rows="3" class="w-full p-2.5 rounded bg-gray-700 border border-gray-600/50 text-white focus:ring-blue-500 focus:border-blue-500 resize-y" placeholder="例如:輕音Joy是哪个博主" style="background:rgba(55,65,81,0)!important;backdrop-filter:blur(4px)"></textarea>
</div>
<button id="sendBtn" class="flex items-center justify-center gap-2 w-full p-3 rounded font-semibold text-white/90 transition duration-150 ease-in-out disabled:opacity-50 disabled:cursor-not-allowed" style="background:rgba(37,99,235,0.75)!important;border:1px solid rgba(255,255,255,0.8)!important;backdrop-filter:blur(8px);box-shadow:0 2px 8px rgba(0,0,0,0.1)" onmouseover="this.style.background='rgba(29,78,216,0.1)'" onmouseout="this.style.background='rgba(37,99,235,0.85)'"><img src="https://www.cloudflare.com/favicon.ico" alt="Cloudflare" class="w-4 h-4"><span class="button-text">发送 Post</span><span id="sendIcon">➤</span><span id="loadingIcon" class="loader hidden"></span></button>
<div id="chat-container" class="mt-6 border-t border-gray-700 pt-4">
<div id="chat" class="flex flex-col space-y-4">
<div class="ai-message"><strong>AI:</strong> 你好!请选择一个模型并输入你的请求。</div>
</div>
<p class="text-yellow-300 font-bold mb-6 text-center text-sm">Powered By Cloudflare Worker Serverless(BETA) | © 2025 輕音Joy </p>
</div>
</div>
<footer class="text-center text-gray-500 text-sm mt-8">
</footer>
<script>
// Wait for the DOM to be fully loaded before executing script logic
document.addEventListener('DOMContentLoaded', () => {
"use strict";
console.log("DOM fully loaded and parsed.");
// --- Element References ---
const chat = document.getElementById('chat');
const chatContainer = document.getElementById('chat-container');
const sendBtn = document.getElementById('sendBtn');
const promptTextarea = document.getElementById('prompt');
const modelSelect = document.getElementById('model');
const sendIcon = document.getElementById('sendIcon');
const loadingIcon = document.getElementById('loadingIcon');
const buttonText = sendBtn ? sendBtn.querySelector('.button-text') : null;
if (!chat || !chatContainer || !sendBtn || !promptTextarea || !modelSelect || !sendIcon || !loadingIcon || !buttonText) {
console.error("CRITICAL ERROR: One or more essential HTML elements not found.");
alert("页面加载错误:无法找到必要的聊天界面元素。请检查HTML结构或稍后重试。");
return; // Stop script execution
}
console.log("All essential elements found.");
function setLoadingState(isLoading) {
console.log(\`setLoadingState called with isLoading: \${isLoading}\`);
// Check elements again just in case, though initial check should suffice
if (!sendBtn || !promptTextarea || !buttonText || !sendIcon || !loadingIcon) {
console.error("Error inside setLoadingState: Required elements missing.");
return;
}
try {
sendBtn.disabled = isLoading;
promptTextarea.disabled = isLoading;
if (isLoading) {
buttonText.textContent = "处理中...";
sendIcon.classList.add('hidden');
loadingIcon.classList.remove('hidden');
} else {
buttonText.textContent = "发送(Post)";
sendIcon.classList.remove('hidden');
loadingIcon.classList.add('hidden');
}
console.log("setLoadingState finished.");
} catch (e) {
console.error("Error executing setLoadingState:", e);
}
}
function addMessage(text, sender = 'ai', isLoading = false) {
function spawnThinkingIcon() {
const icon = document.createElement('img');
icon.src = 'https://i.ibb.co/ch21FSqt/cf.png'; // 你之前的图标地址
icon.className = 'thinking-icon';
document.body.appendChild(icon);
icon.addEventListener('animationend', function() {
icon.remove();
});
}
console.log('addMessage called. Sender: ' + sender + ', isLoading: ' + isLoading);
if (!chat || !modelSelect) {
console.error("Error inside addMessage: Chat or modelSelect element not found.");
return null;
}
try {
let messageDiv = document.createElement('div');
messageDiv.classList.add(sender === 'user' ? 'user-message' : 'ai-message');
const senderStrong = document.createElement('strong');
senderStrong.textContent = sender === 'user' ? '你:' : 'Gemini-AI:';
messageDiv.appendChild(senderStrong);
const contentSpan = document.createElement('span');
contentSpan.className = 'response-content';
if (isLoading) {
const thinkingSpan = document.createElement('span');
thinkingSpan.className = 'thinking';
thinkingSpan.textContent = ' 深度思考中...';
messageDiv.appendChild(thinkingSpan);
messageDiv.appendChild(contentSpan);
spawnThinkingIcon();
} else {
if (sender === 'user') {
contentSpan.textContent = text;
} else {
if (modelSelect.value.startsWith('imagen') && (text.includes('<img') || text.includes('data:image'))) {
contentSpan.innerHTML = text;
} else {
contentSpan.textContent = text;
}
}
messageDiv.appendChild(contentSpan);
}
chat.appendChild(messageDiv);
console.log("Message added to chat.");
scrollToBottom();
return messageDiv;
} catch (e) {
console.error("Error executing addMessage:", e);
return null;
}
}
function scrollToBottom() {
try {
if (chatContainer) {
chatContainer.scrollTop = chatContainer.scrollHeight;
} else {
console.error("Error scrolling: chatContainer not found.");
}
} catch (e) {
console.error("Error executing scrollToBottom:", e);
}
} // END scrollToBottom definition
function escapeHTML(str) {
if (typeof str !== 'string') return '';
const p = document.createElement('p');
p.appendChild(document.createTextNode(str));
return p.innerHTML;
} // END escapeHTML definition
function autoResizeTextarea() {
try {
if (promptTextarea) {
promptTextarea.style.height = 'auto';
promptTextarea.style.height = Math.min(promptTextarea.scrollHeight, 200) + 'px';
} else {
console.error("Error resizing textarea: promptTextarea not found.");
}
} catch (e) {
console.error("Error executing autoResizeTextarea:", e);
}
} // END autoResizeTextarea definition
// --- Main Send Logic Definition ---
async function handleSend() {
console.log("handleSend function started.");
let aiMessageDiv = null; // Define here for broader scope
let responseContentSpan = null;
try {
const prompt = promptTextarea.value.trim();
const model = modelSelect.value;
console.log(\`Prompt: "\${prompt}", Model: "\${model}"\`);
if (!prompt) {
console.log("Prompt is empty. Alerting user.");
alert("请输入你的内容或画面描述!");
promptTextarea.focus();
return; // Stop execution
}
console.log("Setting loading state to true.");
setLoadingState(true); // CALL to setLoadingState
console.log("Adding user message.");
addMessage(prompt, 'user'); // Call to addMessage
promptTextarea.value = ''; // Clear prompt
autoResizeTextarea(); // Call to autoResizeTextarea
console.log("Adding AI placeholder message.");
aiMessageDiv = addMessage('', 'ai', true); // Call to addMessage
if (!aiMessageDiv) {
throw new Error("Failed to create AI placeholder message element.");
}
responseContentSpan = aiMessageDiv.querySelector('.response-content');
const thinkingSpan = aiMessageDiv.querySelector('.thinking');
if (!responseContentSpan) {
throw new Error("Failed to find response content span in AI placeholder.");
}
console.log("AI placeholder added.");
// Scroll after adding placeholder
// scrollToBottom(); // Already called inside addMessage
console.log("Initiating fetch request to worker:", location.href);
const res = await fetch(location.href, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ prompt, model })
});
console.log(\`Workspace response received. Status: \${res.status}, ok: \${res.ok}\`);
if (thinkingSpan) thinkingSpan.remove(); // Remove "Thinking..."
if (!res.ok) {
const errorText = await res.text();
console.error(\`Worker/API Error Response (Status \${res.status}):\`, errorText);
// Update UI
if (responseContentSpan && aiMessageDiv) {
responseContentSpan.textContent = \`请求出错 (\${res.status}): \${escapeHTML(errorText.substring(0, 500))}\${errorText.length > 500 ? '...' : ''}\`;
aiMessageDiv.classList.add('error-message');
scrollToBottom();
} else {
console.error("Cannot display fetch error in chat: message elements not found.");
}
// Throw error to be caught by outer catch block -> triggers finally
throw new Error(\`Server responded with status \${res.status}\`);
}
const selectedModelType = model.startsWith("imagen") ? "imagen" : "gemini";
console.log(\`Handling response for model type: \${selectedModelType}\`);
if (selectedModelType === "gemini") {
console.log("Processing Gemini SSE stream...");
const reader = res.body.getReader();
const decoder = new TextDecoder();
let buffer = '';
let currentText = '';
let loopCount = 0;
while (loopCount < 10000) { // Safety break
loopCount++;
const { done, value } = await reader.read();
if (done) {
console.log("SSE stream finished (done is true).");
break;
}
buffer += decoder.decode(value, { stream: true });
const lines = buffer.split('\\n'); // Split by newline
buffer = lines.pop(); // Keep potential partial line
for (const line of lines) {
if (line.startsWith('data: ')) {
const jsonStr = line.substring(6).trim();
if (jsonStr === '[DONE]' || !jsonStr) continue;
try {
const chunk = JSON.parse(jsonStr);
const textPart = chunk.candidates?.[0]?.content?.parts?.[0]?.text;
if (textPart) {
currentText += textPart;
responseContentSpan.textContent = currentText; // Update UI
scrollToBottom();
} else {
console.log("Received non-text chunk or unexpected structure:", chunk);
if (chunk.promptFeedback?.blockReason) {
currentText += \`\\n[内容被阻止: \${chunk.promptFeedback.blockReason}]\`;
responseContentSpan.textContent = currentText;
aiMessageDiv.classList.add('error-message');
scrollToBottom();
}
}
} catch (e) {
console.error("Error parsing streaming JSON chunk:", e, "Chunk:", jsonStr);
currentText += '\\n[解析数据块时出错]';
responseContentSpan.textContent = currentText;
scrollToBottom();
}
} else if (line.trim()) {
console.log("Received non-data SSE line:", line);
}
} // end for line loop
} // end while loop
if (loopCount >= 10000) console.warn("SSE loop safety break triggered.");
if (buffer.trim()) { // Process remaining buffer
console.warn("Processing remaining buffer after stream end:", buffer);
if (buffer.startsWith('data: ')) {
const jsonStr = buffer.substring(6).trim();
try {
const chunk = JSON.parse(jsonStr);
const textPart = chunk.candidates?.[0]?.content?.parts?.[0]?.text;
if (textPart) {
currentText += textPart;
responseContentSpan.textContent = currentText;
scrollToBottom();
}
} catch (e) {
console.error("Error parsing final buffer:", e);
currentText += '\\n[处理流末尾数据时出错]';
responseContentSpan.textContent = currentText;
scrollToBottom();
}
} else {
console.log("Final buffer does not start with 'data:', content:", buffer);
}
}
console.log("Gemini SSE processing finished.");
} else if (selectedModelType === "imagen") {
console.log("Processing Imagen JSON response...");
try {
const data = await res.json();
console.log("Imagen response JSON parsed:", data); // Log the parsed data structure
if (data.images && data.images.length > 0) {
console.log(\`Found \${data.images.length} images.\`);
responseContentSpan.innerHTML = data.images.map((imgSrc, index) =>
\`<img src="\${imgSrc}" class="my-2 rounded shadow-md" alt="Generated image \${index + 1}" loading="lazy"/>\`
).join('');
} else {
const message = data.message || (data.promptFeedback?.blockReason ? \`请求被阻止: \${data.promptFeedback.blockReason}\` : "未生成任何图像或收到意外响应。");
console.log("No images found or message received:", message);
responseContentSpan.textContent = escapeHTML(message);
if (message.includes("Blocked") || message.includes("Error") || message.includes("出错") || message.includes("Unexpected") || message.includes("阻止")) {
aiMessageDiv.classList.add('error-message');
}
}
scrollToBottom();
} catch (e) {
console.error("Error parsing Imagen JSON response:", e);
// Update UI
if(responseContentSpan && aiMessageDiv){
responseContentSpan.textContent = '解析图像响应时出错:' + e.message;
aiMessageDiv.classList.add('error-message');
scrollToBottom();
}
// Throw error to be caught by outer catch block -> triggers finally
throw new Error('Failed to parse Imagen JSON: ' + e.message);
}
console.log("Imagen JSON processing finished.");
} // End Imagen processing
console.log("handleSend processing completed successfully.");
} catch (error) { // Catch errors from fetch, response processing, or explicitly thrown errors
console.error("!!!! CLIENT-SIDE CATCH BLOCK ERROR in handleSend !!!!:", error);
// Alert removed as it can be annoying, rely on console and chat message
// alert('处理请求时发生错误: ' + error.message);
// Ensure UI reflects error state if possible
if (responseContentSpan) {
// Check if the content is already set by specific error handling above
if (!responseContentSpan.textContent.includes("出错")) {
responseContentSpan.textContent = '客户端错误: ' + error.message;
}
if (aiMessageDiv && !aiMessageDiv.classList.contains('error-message')) {
aiMessageDiv.classList.add('error-message');
}
scrollToBottom(); // Scroll to show error
} else {
console.error("Cannot display error in chat bubble: responseContentSpan not found.");
}
} finally { // This block ALWAYS runs
console.log("!!!! CLIENT-SIDE FINALLY BLOCK in handleSend !!!!");
setLoadingState(false); // Ensure UI is re-enabled
promptTextarea.focus(); // Put cursor back
console.log("UI re-enabled.");
}
} // END handleSend definition
// --- Attach Event Listeners ---
sendBtn.addEventListener('click', handleSend);
console.log("Send button click listener attached.");
promptTextarea.addEventListener('keypress', (e) => {
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault();
console.log("Enter key pressed, triggering handleSend.");
handleSend(); // Call the main handler
}
});
console.log("Textarea keypress listener attached.");
promptTextarea.addEventListener('input', autoResizeTextarea);
console.log("Textarea input listener attached.");
// --- Initial Setup Calls ---
autoResizeTextarea(); // Resize initially
console.log("Initial textarea resize done.");
// scrollToBottom(); // Optional: Scroll down initially if needed
}); // END DOMContentLoaded listener
</script>
</body>
</html>
`; // End of the main template literal
} // End of renderHTML
// ========================================================================== //
// ===================== CLOUDFLARE WORKER ENTRY POINT ====================== //
// ========================================================================== //
export default {
async fetch(request, env, ctx) {
// Assign a unique ID for request tracing
const requestId = request.headers.get('cf-ray') || crypto.randomUUID();
const logPrefix = `[${requestId}]`;
console.log(`${logPrefix} Worker received request: ${request.method} ${request.url}`);
// --- Hardcoded API Key (FOR TESTING ONLY - INSECURE) ---
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
// >>>>>>>> IMPORTANT: REPLACE WITH YOUR ACTUAL VALID API KEY <<<<<<<
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
const GEMINI_API_KEY = env.GEMINI_API_KEY;
// 检查环境变量是否配置
if (!GEMINI_API_KEY || GEMINI_API_KEY.length < 30) {
console.error(`${logPrefix} CRITICAL ERROR: API Key 未配置或无效`);
return new Response("Server Configuration Error: Invalid API Key.", {
status: 500,
headers: { "Content-Type": "text/plain; charset=utf-8", ...corsHeaders() }
});
}
// --- CORS Preflight ---
if (request.method === "OPTIONS") {
console.log(`${logPrefix} Responding to OPTIONS request.`);
return new Response(null, { status: 204, headers: corsHeaders() });
}
// --- Serve HTML for GET ---
if (request.method === "GET") {
console.log(`${logPrefix} Responding to GET request with HTML.`);
try {
const html = renderHTML();
return new Response(html, {
headers: { "Content-Type": "text/html; charset=utf-8", ...corsHeaders() },
});
} catch (e) {
console.error(`${logPrefix} Error rendering HTML:`, e);
return new Response("Internal Server Error rendering page.", { status: 500 });
}
}
// --- Handle POST for API calls ---
if (request.method === "POST") {
console.log(`${logPrefix} Processing POST request.`);
let requestBody;
try {
requestBody = await request.json();
// Avoid logging full prompt if sensitive, log excerpt or confirmation
console.log(`${logPrefix} Parsed request body. Model: ${requestBody?.model}, Prompt starts with: ${String(requestBody?.prompt).substring(0,30)}...`);
} catch (e) {
console.error(`${logPrefix} Invalid JSON body received:`, e);
return new Response("Invalid JSON body.", {
status: 400, headers: { "Content-Type": "text/plain; charset=utf-8", ...corsHeaders() }
});
}
const { prompt, model } = requestBody;
if (!prompt || !model) {
console.error(`${logPrefix} Missing prompt or model in request body.`);
return new Response("Missing prompt or model in request body.", {
status: 400, headers: { "Content-Type": "text/plain; charset=utf-8", ...corsHeaders() }
});
}
const allowedModels = ["imagen-3.0-generate-002", "gemini-2.5-flash-preview-04-17"];
if (!allowedModels.includes(model)) {
console.error(`${logPrefix} Invalid model selected: ${model}`);
return new Response(`Invalid model selected: ${model}. Allowed: ${allowedModels.join(", ")}`, {
status: 400, headers: { "Content-Type": "text/plain; charset=utf-8", ...corsHeaders() }
});
}
// --- Prepare Google API Request ---
const isImagen = model.startsWith("imagen");
const apiEndpoint = isImagen ? 'generateContent' : 'streamGenerateContent';
const apiUrl = `https://generativelanguage.googleapis.com/v1beta/models/${model}:${apiEndpoint}?key=${GEMINI_API_KEY}${isImagen ? '' : '&alt=sse'}`;
console.log(`${logPrefix} Target API URL: ${apiUrl}`); // Log URL (Key is visible here, acceptable for testing logs)
const apiRequestBody = isImagen
? { contents: [{ role: "user", parts: [{ text: prompt }] }], generationConfig: { candidateCount: 1 } } // Request 1 image for Imagen
: { contents: [{ parts: [{ text: prompt }] }] }; // Simple content for Gemini
// --- Call Google API ---
try {
console.log(`${logPrefix} Sending request to Google API...`);
const apiResponse = await fetch(apiUrl, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(apiRequestBody)
});
console.log(`${logPrefix} Google API response status: ${apiResponse.status}, ok: ${apiResponse.ok}`);
// --- Handle API Error Response ---
if (!apiResponse.ok) {
const errorBodyText = await apiResponse.text(); // Read error body
console.error(`${logPrefix} Google API Error (${apiResponse.status}): ${errorBodyText}`);
let userFriendlyError = `Google API Error (${apiResponse.status})`;
try { // Attempt to parse standard Google API error JSON
const errorJson = JSON.parse(errorBodyText);
userFriendlyError += `: ${errorJson.error?.message || 'Unknown error structure.'}`;
} catch (e) { // Fallback to raw text if not JSON
userFriendlyError += `: ${errorBodyText.substring(0, 200)}${errorBodyText.length > 200 ? "..." : ""}`;
}
// Return error TO CLIENT in appropriate format
if (isImagen) { // Imagen expects JSON response
return new Response(JSON.stringify({ images: [], message: userFriendlyError }), {
status: apiResponse.status, // Use original Google status code
headers: { "Content-Type": "application/json", ...corsHeaders() }
});
} else { // Gemini streaming expects text/event-stream on success, return plain text error
return new Response(userFriendlyError, {
status: apiResponse.status, // Use original Google status code
headers: { "Content-Type": "text/plain; charset=utf-8", ...corsHeaders() }
});
}
} // End API Error Handling
// --- Handle API Success Response ---
if (isImagen) { // Process Imagen JSON response
console.log(`${logPrefix} Processing successful Imagen response.`);
const responseBodyText = await apiResponse.text();
let data;
try {
data = JSON.parse(responseBodyText);
// Avoid logging potentially large base64 data unless necessary
console.log(`${logPrefix} Parsed Imagen JSON successfully. Candidates count: ${data.candidates?.length}`);
} catch (parseError) {
console.error(`${logPrefix} Error parsing Imagen JSON response:`, parseError, "Body snippet:", responseBodyText.substring(0, 500));
return new Response(JSON.stringify({ images: [], message: "Internal Server Error: Failed to parse Imagen API response." }), {
status: 500, headers: { "Content-Type": "application/json", ...corsHeaders() }
});
}
// Check for safety blocks or other issues within the 'successful' response
if (data.promptFeedback?.blockReason) {
console.warn(`${logPrefix} Imagen request blocked: ${data.promptFeedback.blockReason}`);
return new Response(JSON.stringify({ images: [], message: `请求被阻止: ${data.promptFeedback.blockReason}` }), {
status: 200, // Technically API call succeeded, but content blocked
headers: { "Content-Type": "application/json", ...corsHeaders() }
});
}
// Check if candidates array exists and has content
if (!data.candidates || data.candidates.length === 0 || !data.candidates[0].content?.parts) {
console.warn(`${logPrefix} Imagen response ok, but no valid candidates/parts found.`);
return new Response(JSON.stringify({ images: [], message: "API success, but no generated images found in response." }), {
status: 200, headers: { "Content-Type": "application/json", ...corsHeaders() }
});
}
// Extract image data
const imageUrls = data.candidates[0].content.parts
.filter(part => part.inlineData?.mimeType?.startsWith("image/"))
.map(part => `data:${part.inlineData.mimeType};base64,${part.inlineData.data}`);
if (imageUrls.length > 0) {
console.log(`${logPrefix} Found ${imageUrls.length} images. Sending JSON response.`);
return new Response(JSON.stringify({ images: imageUrls }), {
headers: { "Content-Type": "application/json", ...corsHeaders() }
});
} else {
console.warn(`${logPrefix} Imagen response ok and candidates exist, but no image parts found.`);
return new Response(JSON.stringify({ images: [], message: "API success, but no image data found in response parts." }), {
status: 200, headers: { "Content-Type": "application/json", ...corsHeaders() }
});
}
} else { // Stream Gemini SSE response
console.log(`${logPrefix} Streaming Gemini response back to client.`);
// Use TransformStream for pass-through
const { readable, writable } = new TransformStream();
// Pipe the response body to the writable end. Handle potential errors during piping.
apiResponse.body.pipeTo(writable).catch(err => {
console.error(`${logPrefix} Error piping Gemini stream:`, err);
// Difficult to signal error back to client once headers are sent
});
// Set appropriate headers for SSE
const responseHeaders = new Headers({
"Content-Type": "text/event-stream; charset=utf-8",
"Cache-Control": "no-cache",
"Connection": "keep-alive",
...corsHeaders() // Apply CORS headers
});
// Return the readable end of the stream
return new Response(readable, {
status: 200, // Successful stream initiation
headers: responseHeaders
});
} // End Gemini Streaming
} catch (error) { // Catch network errors during fetch to Google API
console.error(`${logPrefix} Worker fetch error calling Google API:`, error);
const errorMsg = `Internal Server Error calling Google API: ${error.message}`;
if (isImagen) {
return new Response(JSON.stringify({ images: [], message: errorMsg }), {
status: 500, headers: { "Content-Type": "application/json", ...corsHeaders() }
});
} else {
return new Response(errorMsg, {
status: 500, headers: { "Content-Type": "text/plain; charset=utf-8", ...corsHeaders() }
});
}
}
} // End POST handler
// --- Method Not Allowed ---
console.log(`${logPrefix} Method Not Allowed: ${request.method}`);
return new Response("Method Not Allowed", {
status: 405,
headers: { "Allow": "GET, POST, OPTIONS", ...corsHeaders() }
});
} // End async fetch
}; // End export default
================================================
FILE: LICENSE
================================================
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.
================================================
FILE: README.md
================================================
<p align="center">
<a href="https://www.cloudflare.com/"><img src="https://cf-assets.www.cloudflare.com/zkvhlag99gkb/msyMXSSf3hlUnawe68PDG/d0edfa4f2703a94018c7ab65d9808616/45DEDC7B-B31F-461C-B786-12FBAF1A5391.png" alt="Cloudflare Workers" width="700"/></a>
</p>
<h1 align="center">Ultra Cloudflare☁️Serverless AI worker</h1>
<p align="center">
<strong>EN:</strong> A simple yet powerful Cloudflare Worker to proxy requests to APIs. Enables access to advanced AI models from the edge, securely managing API keys and bypassing regional restrictions.Also available for others popular worker.Gonna have R2 and D2 in the later versions
<br><strong>ZH:</strong> 一个简洁而强大的Cloudflare Worker,用于转发API请求至各大AI平台,并且将全球各地的计算节点靠近用户部署,使得您可以从边缘访问高级AI模型,结合KV安全管理API密钥,并绕过地域限制同时支持其他主流平台worker,后期将拓展R2和D1数据库支持
<br><strong>RU:</strong>Простой, но мощный Cloudflare Worker для проксирования запросов API. Обеспечивает доступ к передовым ИИ-моделям с периферии, безопасно управляя API-ключами и обходя региональные ограничения. Поддерживает интеграцию с другими Worker-платформами, в будущем планируется расширение с использованием баз данных R2 и D1.
<b4>
</p>
<p align="center">
<a href="https://discord.gg/sQVz6vtf"><img src="https://img.shields.io/discord/1018870125102895134?logo=discord" alt="chat"></a>
<a href="https://github.com/qyjoy/AI-worker/stargazers"><img src="https://img.shields.io/github/stars/qyjoy/AI-worker?style=social" alt="GitHub Stars"></a>
<a href="https://github.com/qyjoy/AI-worker/issues"><img src="https://img.shields.io/github/issues/qyjoy/AI-worker?style=flat-square&color=orange" alt="GitHub Issues"></a>
<a href="https://github.com/qyjoy/AI-worker/blob/main/LICENSE"><img src="https://img.shields.io/github/license/qyjoy/AI-worker?style=flat-square&color=blue" alt="License"></a>
<a href="https://workers.cloudflare.com/" target="_blank" rel="noopener noreferrer"><img src="https://img.shields.io/badge/Cloudflare%20Workers-Ready-orange?style=flat-square&logo=cloudflare" alt="Cloudflare Workers Ready"></a>
<a href="https://gemini.google.com/" target="_blank" rel="noopener noreferrer" style="text-decoration:none;display:inline-flex;align-items:center;"><img src="https://img.shields.io/badge/Google-4285F4?style=flat-square&logo=googlegemini&logoColor=fff" alt="Google Gemini" style="border-radius:0 0 0 0;"><img src="https://img.shields.io/badge/Gemini-886FBF?style=flat-square&logo=&logoColor=fff" alt="Gemini" style="border-radius:0 0 0 0;"></a>
</p>
<p align="center">
<em>Free, Private Gemini Access via Cloudflare. No VPN needed for restricted Countries. Full Control, with GPL 3.0 protocol</em>
<br>
<em>通过Cloudflare免费、私有化访问和管理Gemini~摆脱地域限制无烦恼,完全由自己掌控,原生gemini等AI模型,支持上传图片,录音等</em>
</p>
## 🌐 Overview | 概述
<a><img src="https://cf-assets.www.cloudflare.com/zkvhlag99gkb/4CNamrq69wPhKeFeFQBNe4/b65099939b3140c3cf947898ffea271f/Workers-diagram-MVP--copy-3_3x-8--1-.png" alt="Cloudflare Workers" width="700"/></a><br>
**EN:** This Cloudflare Worker allows you to:
* Access Google's powerful AI models from anywhere, including regions where direct access might be challenging.
* Securely manage your Google AI API key using Cloudflare's environment variables, keeping it out of client-side code.
* Provide a simple, customizable HTML interface for interacting with the AI.
* Leverage Cloudflare's global network for potentially lower latency and high scalability.

<br>Before: Your area > Not allow to access > AI ×
<br>Now : Your area > Cloudflare Worker > AI √
<br>**ZH:** 此Cloudflare Worker允许您:
* 从任何地方访问Google强大的AI模型,包括那些可能难以直接访问的地区。
* 使用Cloudflare的环境变量安全地管理您的AI API(Gemini,ChatGPT等)密钥,避免其暴露在客户端代码中。
* 提供一个简单、可定制的HTML界面与AI进行交互。
* 利用Cloudflare的全球网络实现潜在的低延迟和高可扩展性。
## 🎈 Features | 功能

* **🎯 Proxy AI Requests / 转发AI请求:**
* EN:Or you could say it's"Forward AI request", whatever, anyway → Securely routes requests to AIchat and Imagen APIs.
* ZH: 安全地将请求API转发到AI源站点
* **🔑 API Key Management / API密钥管理:**
* EN: Store your API key securely in Cloudflare Worker environment variables.
* ZH: 将您的API密钥安全地存储在Cloudflare Worker环境变量中。
* **📄 Simple HTML Interface / 简单的HTML界面:**
* EN: Includes a user-friendly HTML front-end with theme selection for easy interaction.
* ZH: 包含一个用户友好的HTML前端,并提供主题选择,方便交互。
* **🔄 CORS Handling / CORS处理:**
* EN: Pre-configured to handle Cross-Origin Resource Sharing.
* ZH: 已预先配置处理跨域资源共享(CORS)。
* **💨 Supports Streaming / 支持流式传输:**
* EN: Handles streaming text responses from models like Gemini/GPT for real-time output.
* ZH: 支持从Gemini/GPT等模型获取流式文本响应,实现实时输出。
* **🖼️ Supports Image Generation / 支持图像生成:**
* EN: Handles image generation requests and displays results from Imagen.
* ZH: 支持处理图像生成请求并显示来自Imagen的结果。
* **🌍 No VPN Proxy Required / 访问无需翻牆挂代理:**
* EN: For users in regions with restricted access, this proxy on Cloudflare's network can enable access without a VPN for the end-user.
* ZH: 对于某些地区可能无法直接访问Google API的用户,在Cloudflare的网络上部署此代理可以让最终用户无需翻墙即可访问。

## 👍 Advantages of using Cloudflare Workers | 使用Cloudflare Worker的优点
**EN:**
* **💸 Serverless & Cost-Effective:** No server management needed. The free tier is often generous enough for personal projects.
* **⚡ Edge Deployment:** Runs closer to your users, reducing latency and DDos attack barely register thanks to Cloudflare's auto mitigation
* **📈 Scalability:** Automatically scales with traffic.
* **🚀 Ease of Deployment:** Deploy directly from the Cloudflare dashboard or via Wrangler CLI.
* **🔒 Secure API Key Handling:** Keep your API keys safe using encrypted environment variables.

**ZH:**
* **💸 无服务器且经济高效:** 无需管理服务器。免费套餐通常足以满足个人项目需求。
* **⚡ 边缘部署:** 更接近用户运行,减少延迟,抗DDos,支持多种平台worker
* **📈 可扩展性:** 随流量自动扩展。
* **🚀 易于部署:** 可直接通过Cloudflare等平台控制台或Wrangler CLI部署。
* **🔒 安全的API密钥处理:** 使用加密的环境变量安全保管您的API密钥。
## 🚀 Setup & Deployment | 设置与部署 <img src="https://github.com/user-attachments/assets/0c014e9d-9c97-430e-b339-f63c91665d7f" alt="cloudflare icon" style="height: 20px; vertical-align: middle;">
Follow these steps to deploy your own instance:
请按照以下步骤部署您自己的实例:
1. **Create a Cloudflare Worker | 创建Cloudflare Worker:**
* EN: Log in to your Cloudflare dashboard, navigate to "Workers & Pages", and click "Create application", then "Create Worker". Give it a name (e.g., `ultra-ai-proxy`).
* ZH: 登录到您的Cloudflare控制台,导航到“Workers & Pages”,点击“创建应用程序”,然后选择“创建Worker”。为其命名(例如 `ultra-ai-proxy`)。
2. **Configure the Worker | 配置Worker:**
* EN: Click "Configure Worker" or "Quick edit" for your newly created worker.
* ZH: 点击新创建Worker的“配置Worker”或“快速编辑”。
3. **Paste the Code Files | 粘贴代码文件:**
* EN: The project is modular. You'll need to create/replace the following files in the Cloudflare online editor with the provided code:
* `worker.js` (or `index.js` if that's your main file name in the editor)
* `request-handler.js`
* `api-handler.js`
* `html-renderer.js`
* `utils.js`
* ZH: 本项目是模块化的。您需要在Cloudflare在线编辑器中创建/替换以下文件,并使用本项目提供的代码:
* `worker.js` (如果在编辑器中您的主文件名是 `index.js`,则使用该名称)
* `request-handler.js`
* `api-handler.js`
* `html-renderer.js`
* `utils.js`
* *(You can find the code for these files in this repository or from where you received them.)*
4. **Add Environment Variable for API Key | 添加API密钥环境变量:**
* EN: Go to your Worker's **Settings** tab, then **Variables**.
* Under **Environment Variables**, click **"Add variable"**.
* **Variable name:** `GEMINI_API_KEY`
* **Value:** Your actual Google AI Studio or Google Cloud Vertex AI API Key.
* **IMPORTANT:** Click the **"Encrypt"** button next to the value field to secure your API key.

* ZH: 进入Worker的 **设置 (Settings)** 选项卡, 然后选择 **变量 (Variables)**。
* 在 **环境变量 (Environment Variables)** 部分, 点击 **"添加变量 (Add variable)"**。
* **变量名称 (Variable name):** `GEMINI_API_KEY`
* **值 (Value):** 您真实的 Google AI Studio 或 Google Cloud Vertex AI API 密钥。
* **重要:** 点击值字段旁边的 **"加密 (Encrypt)"** 按钮以保护您的API密钥。
5. **Save and Deploy | 保存并部署:**
* EN: After adding the code and the environment variable, click the **"Save and Deploy"** button in the editor or on the Worker's settings page.
* ZH: 添加代码和环境变量后,在编辑器或Worker的设置页面点击 **"保存并部署 (Save and Deploy)"** 按钮。
Your AI proxy should now be live at the URL provided by Cloudflare (e.g., `your-worker-name.your-subdomain.workers.dev`).
您的AI代理现在应该已在Cloudflare提供的URL上激活(例如 `your-worker-name.your-subdomain.workers.dev`)。
## 🛠️ Usage | 使用方法
* **EN:** Simply navigate to your Worker's URL in a web browser. You'll see the HTML interface.
* Select a model from the dropdown.
* Choose a theme.
* Type your prompt or image description into the textarea.
* Click "发送 Post".
* **ZH:** 在网页浏览器中直接访问您的Worker URL。您将看到HTML界面。
* 从下拉菜单中选择一个模型。
* 选择一个主题。
* 在文本区域输入您的问题或画面描述。
* 点击“发送 Post”按钮。
### Customization | 自定义
* **HTML & CSS:** Modify `html-renderer.js` to change the look and feel of the front-end.
* **Models:** Update the `allowedModels` array in `api-handler.js` if new Gemini/Imagen models are released or if you want to restrict options.
* **Themes:** Add or modify themes in the `themeConfig` object within the client-side script in `html-renderer.js`.
### 🔄 贡献指南/Contributer
请基于 `discover` 分支开发您的功能并提交 Pull Request。会定期从 `discover` 中精选高质量的更改合并进 `main`。
或联系开发者邮箱:dev@qyjoy.vip
### ⚠️ 澄清:“API 转发 / API 代理” ≠ “网络代理”Clarification: “API Forwarding / API Proxy” ≠ “Network Proxy”
**ZH**
有些用户担心本项目因“代理”字样是否违反 Cloudflare 服务条款,这里做一个清晰的技术澄清:
本项目属于**API 转发 / API 代理(API forwarder / proxy)**,**不是网络代理(Network Proxy)**。
- ✅ 它仅转发请求到**特定的公开 API(如 Google 的 Gemini 和 Imagen)**
- ❌ 它不支持访问任意网站
- ❌ 它不提供 VPN、SOCKS5、Shadowsocks、Trojan 等网络代理协议或服务
Cloudflare 所禁止的“网络代理”,指的是通用数据转发或翻墙用途的工具。而本项目只是通过 Cloudflare Worker 将 Web 前端请求安全透明地转发给合法 API 服务,功能专一、无滥用空间。
因此,本项目**完全符合 Cloudflare 使用政策**,是 Cloudflare Worker 的标准合规用例。
---
### 📊 API 转发 vs. 网络代理 对比表
| 特性 / Feature | API Forward (API Proxy) | Network Proxy (VPN/SOCKS/Shadowsocks 等) |
|-------------------------------------------|------------------------------------------------|----------------------------------------------|
| 🔌 访问范围 | 指定 API 服务(如 Gemini,Imagen,GPT 等) | 任意网站、应用程序、通用网络流量 |
| 🔍 ISO Layer | 基于7层的应用转发 | 基于4层的网络包代理 |
| 📦 数据内容 | 请求和响应均为结构化 API 数据(如 JSON) | 原始 IP 包或加密流量(如 TCP、UDP) |
| 🧠 用途 | 前端→Worker→API 安全转发,用于接口调用 | 匿名访问、翻墙、绕过网络限制 |
| 🔐 安全性 | 精确控制目标 API,不可滥用 | 可被用于非法流量、IP 池攻击、绕过审查等 |
| 🛠️ 底层协议 | HTTPS 请求转发 | TCP/IP 层或自定义加密隧道协议(如 VPN) |
| ☁️ Cloudflare 是否允许使用 | ✅ 是,属于 Cloudflare Worker 正常用途 | ❌ 否,违反 Acceptable Use Policy |
| ⚙️ 部署复杂度 | 低:纯 Worker 脚本 + API 配置 | 高:需要服务端、端口映射、防火墙规则等 |
| 🎯 示例项目 | Cloudflare Worker 转发 Gemini/chatGPT等 API | Clash、Trojan、V2Ray、Shadowsocks 等工具 |
> ✅ 本项目使用的是 **API Forward** 模式,完全符合 Cloudflare 的服务政策,安全、可控、稳定。
**EN:**
Some users have asked whether this project violates Cloudflare's Terms of Service because of the term "proxy" being used. Let's clarify:
This project is an **API forwarder / API proxy**, not a **network proxy**.
- ✅ It only relays requests to **specific public APIs** (e.g., Google Gemini, Imagen, etc.)
- ❌ It does **not** allow general access to arbitrary websites
- ❌ It does **not** provide tunnels, SOCKS5, Shadowsocks, or VPN-like services
In Cloudflare’s terms, a **network proxy** refers to tools that allow general traffic routing and circumvention of regional restrictions. This project does none of that.
Therefore, this project **fully complies** with Cloudflare’s Acceptable Use Policy and is a **legitimate use of Cloudflare Workers** to route frontend API requests through serverless infrastructure.
> 🔒 This is safe, legal, and compliant. 安全合规,放心部署。
## 📝 License | 许可证
**EN:** This project is free software: you can redistribute it and/or modify it under the terms of the **GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.**
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>.
**ZH:** 本项目是自由软件:您可以根据 **自由软件基金会发布的GNU通用公共许可证的条款重新分发和/或修改它,无论是许可证的第3版,还是(根据您的选择)任何更高版本。**
分发本程序是希望它能有用,但没有任何担保;甚至没有对适销性或特定用途适用性的暗示担保。更多详情请参阅GNU通用公共许可证。
您应该已经随本程序收到一份GNU通用公共许可证的副本。如果没有,请参阅 <https://www.gnu.org/licenses/>。
You can find the full license text in the [LICENSE](LICENSE) file.
您可以在 [LICENSE](LICENSE) 文件中找到完整的许可证文本。
---
## Star History
[](https://star-history.com/#qyjoy/AI-Worker&Date)

<p align="center">
Made with ❤️ by 輕音Joy with AI Optimization
<br>
<em>If you find this useful, please consider giving a ⭐!</em>
</p>
================================================
FILE: V3(stable)/api-handler.js
================================================
// api-handler.js
// Handles communication with the Google Generative AI API.
import { corsHeaders } from './utils.js';
export async function handleApiCall(request, env, logPrefix) {
console.log(`${logPrefix} Processing POST request for API call.`);
let requestBody;
try {
requestBody = await request.json();
console.log(`${logPrefix} Parsed request body. Model: ${requestBody?.model}, Prompt starts with: ${String(requestBody?.prompt).substring(0, 30)}...`);
} catch (e) {
console.error(`${logPrefix} Invalid JSON body received:`, e);
return new Response("Invalid JSON body.", {
status: 400, headers: { "Content-Type": "text/plain; charset=utf-8", ...corsHeaders() }
});
}
const { prompt, model } = requestBody;
if (!prompt || !model) {
console.error(`${logPrefix} Missing prompt or model in request body.`);
return new Response("Missing prompt or model in request body.", {
status: 400, headers: { "Content-Type": "text/plain; charset=utf-8", ...corsHeaders() }
});
}
// Extended list of models based on comments in original HTML
const allowedModels = [
"gemini-2.5-flash-preview-04-17", // Default and explicitly mentioned
"gemini-1.5-pro-preview-0409",
"gemini-1.5-flash-preview-0514",
"gemini-pro",
"gemini-pro-vision",
"imagen-3.0-generate-002" // Example Imagen model
// Add other specific Imagen model versions if known, e.g., "imagen-..."
];
if (!allowedModels.includes(model) && !model.startsWith("imagen")) { // Allow any model starting with "imagen" for flexibility
console.error(`${logPrefix} Invalid model selected: ${model}`);
return new Response(`Invalid model selected: ${model}. Allowed: ${allowedModels.join(", ")} or any 'imagen-...' model.`, {
status: 400, headers: { "Content-Type": "text/plain; charset=utf-8", ...corsHeaders() }
});
}
const GEMINI_API_KEY = env.GEMINI_API_KEY;
const isImagen = model.startsWith("imagen");
const apiEndpoint = isImagen ? 'generateContent' : 'streamGenerateContent';
// Note: v1beta is used. For stable versions, it might be v1.
const apiVersion = "v1beta"; // Or "v1" if you are using stable models without "preview" in their names.
const apiUrl = `https://generativelanguage.googleapis.com/${apiVersion}/models/${model}:${apiEndpoint}?key=${GEMINI_API_KEY}${isImagen ? '' : '&alt=sse'}`;
console.log(`${logPrefix} Target API URL: ${apiUrl}`);
const apiRequestBody = isImagen
? { contents: [{ role: "user", parts: [{ text: prompt }] }], generationConfig: { candidateCount: 1 } }
: { contents: [{ parts: [{ text: prompt }] }] };
try {
console.log(`${logPrefix} Sending request to Google API...`);
const apiResponse = await fetch(apiUrl, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(apiRequestBody)
});
console.log(`${logPrefix} Google API response status: ${apiResponse.status}, ok: ${apiResponse.ok}`);
if (!apiResponse.ok) {
const errorBodyText = await apiResponse.text();
console.error(`${logPrefix} Google API Error (${apiResponse.status}): ${errorBodyText}`);
let userFriendlyError = `Google API Error (${apiResponse.status})`;
try {
const errorJson = JSON.parse(errorBodyText);
userFriendlyError += `: ${errorJson.error?.message || 'Unknown error structure.'}`;
} catch (e) {
userFriendlyError += `: ${errorBodyText.substring(0, 200)}${errorBodyText.length > 200 ? "..." : ""}`;
}
if (isImagen) {
return new Response(JSON.stringify({ images: [], message: userFriendlyError }), {
status: apiResponse.status, headers: { "Content-Type": "application/json", ...corsHeaders() }
});
} else {
return new Response(userFriendlyError, {
status: apiResponse.status, headers: { "Content-Type": "text/plain; charset=utf-8", ...corsHeaders() }
});
}
}
if (isImagen) {
console.log(`${logPrefix} Processing successful Imagen response.`);
const responseBodyText = await apiResponse.text();
let data;
try {
data = JSON.parse(responseBodyText);
console.log(`${logPrefix} Parsed Imagen JSON successfully. Candidates count: ${data.candidates?.length}`);
} catch (parseError) {
console.error(`${logPrefix} Error parsing Imagen JSON response:`, parseError, "Body snippet:", responseBodyText.substring(0, 500));
return new Response(JSON.stringify({ images: [], message: "Internal Server Error: Failed to parse Imagen API response." }), {
status: 500, headers: { "Content-Type": "application/json", ...corsHeaders() }
});
}
if (data.promptFeedback?.blockReason) {
console.warn(`${logPrefix} Imagen request blocked: ${data.promptFeedback.blockReason}`);
return new Response(JSON.stringify({ images: [], message: `请求被阻止: ${data.promptFeedback.blockReason}` }), {
status: 200, headers: { "Content-Type": "application/json", ...corsHeaders() }
});
}
if (!data.candidates || data.candidates.length === 0 || !data.candidates[0].content?.parts) {
console.warn(`${logPrefix} Imagen response ok, but no valid candidates/parts found.`);
return new Response(JSON.stringify({ images: [], message: "API success, but no generated images found in response." }), {
status: 200, headers: { "Content-Type": "application/json", ...corsHeaders() }
});
}
const imageUrls = data.candidates[0].content.parts
.filter(part => part.inlineData?.mimeType?.startsWith("image/"))
.map(part => `data:${part.inlineData.mimeType};base64,${part.inlineData.data}`);
if (imageUrls.length > 0) {
console.log(`${logPrefix} Found ${imageUrls.length} images. Sending JSON response.`);
return new Response(JSON.stringify({ images: imageUrls }), {
headers: { "Content-Type": "application/json", ...corsHeaders() }
});
} else {
console.warn(`${logPrefix} Imagen response ok and candidates exist, but no image parts found.`);
return new Response(JSON.stringify({ images: [], message: "API success, but no image data found in response parts." }), {
status: 200, headers: { "Content-Type": "application/json", ...corsHeaders() }
});
}
} else { // Gemini SSE stream
console.log(`${logPrefix} Streaming Gemini response back to client.`);
const { readable, writable } = new TransformStream();
apiResponse.body.pipeTo(writable).catch(err => {
console.error(`${logPrefix} Error piping Gemini stream:`, err);
});
const responseHeaders = new Headers({
"Content-Type": "text/event-stream; charset=utf-8",
"Cache-Control": "no-cache",
"Connection": "keep-alive",
...corsHeaders()
});
return new Response(readable, { status: 200, headers: responseHeaders });
}
} catch (error) {
console.error(`${logPrefix} Worker fetch error calling Google API:`, error);
const errorMsg = `Internal Server Error calling Google API: ${error.message}`;
if (isImagen) {
return new Response(JSON.stringify({ images: [], message: errorMsg }), {
status: 500, headers: { "Content-Type": "application/json", ...corsHeaders() }
});
} else {
return new Response(errorMsg, {
status: 500, headers: { "Content-Type": "text/plain; charset=utf-8", ...corsHeaders() }
});
}
}
}
================================================
FILE: V3(stable)/html-rendererv3.js
================================================
// html-renderer.js// Generates the complete HTML page, including CSS and client-side JavaScript.// CSS styles for the page
const getStyles = () => `
<style>
:root {
--table-bg-rgb: 0, 0, 0;
--error-message-rgb: 185, 28, 28;
--user-text-rgb: 255, 255, 255;
--ai-text-rgb: 255, 255, 255;
--link-text-rgb: 199, 210, 254;
--theme-primary-rgb: 29, 78, 216; /* default */
--table-hover-rgb: 74, 85, 104;
--input-border-rgb: 55, 65, 81;
--table-border-rgb: 55, 65, 81;
--table-header-rgb: 30, 41, 59;
}
.w-full.max-w-6xl {background-color: rgba(var(--theme-bg-rgb), 0.85)!important;}
#chat > div {background-color: rgba(var(--user-message-rgb), 0.8);}
.ai-message { background-color: rgba(var(--ai-message-rgb), 0.8);}
#prompt, #sendBtn, select { background-color: rgba(var(--input-bg-rgb), 0.5)!important;}
#sendBtn:hover { background-color: rgba(var(--theme-primary-rgb), 0.6)!important;}
.user-message { background-color: rgba(var(--user-message-rgb), 0.8);}
.ai-message > strong::before {content: "";display: inline-block;width: 20px;height: 20px;background-image: url('https://www.gstatic.com/lamda/images/sparkle_resting_v2_1ff6f6a71f2d298b1a31.gif');background-size: contain;background-repeat: no-repeat;margin-right: 8px;vertical-align: middle;}
.text-3xl{background:linear-gradient(90deg,red,orange,yellow,green,blue,purple,red);-webkit-background-clip:text;background-clip:text;color:transparent;background-size:500% auto;animation:rainbow 10s linear infinite}@keyframes rainbow{0%{background-position:0}100%{background-position:500%}}
@keyframes textGlow{0%{text-shadow:0 0 10px rgba(var(--theme-primary-rgb),.8),0 0 20px rgba(var(--theme-primary-rgb),.6);transform:scale(1)}50%{text-shadow:0 0 30px rgba(var(--theme-primary-rgb),.9),0 0 50px rgba(var(--theme-primary-rgb),.8),0 0 70px rgba(var(--theme-primary-rgb),.6);transform:scale(1.05)}100%{text-shadow:0 0 10px rgba(var(--theme-primary-rgb),.8),0 0 20px rgba(var(--theme-primary-rgb),.6);transform:scale(1)}}#prompt{background-color:rgba(var(--input-bg-rgb),0.5)!important}
.thinking{animation:textGlow 1.5s ease-in-out infinite;color:#a78bfa!important;font:italic bold 1.2em sans-serif}
@keyframes icon2DRotate {0% { opacity: 0; transform: scale(0) rotateY(0deg); } 10% { opacity: 1; transform: scale(3) rotateY(0deg); } 50% { transform: scale(3) rotateY(180deg); } 90% { transform: scale(3) rotateY(350deg); } 100% { opacity: 0; transform: scale(0) rotateY(360deg); }}
.thinking-icon {position: absolute; top: 30%; left: 50%;width: 80px; height: 80px; margin: -40px 0 0 -40px;pointer-events: none;animation: icon2DRotate 6s ease-in-out forwards;transform-origin: center center;transform-style: preserve-3d;filter: drop-shadow(0 0 25px #dba0ff) brightness(1.5) saturate(1.8);z-index: 999;}
body {background: url('https://www.sensecore.cn/upload/20230330/crjfafitbja7qufwrt.jpg') no-repeat center center fixed;background-size: cover;}
.w-full.max-w-6xl {background-color: rgba(31, 41, 55, 0.85)!important;backdrop-filter: blur(4px);}
#chat > div {background-color: rgba(30, 64, 175, 0.8);} /* User messages default, AI messages override this */
.ai-message {background-color: rgba(55, 65, 81, 0.8);}
#chat > div { margin-bottom: 1rem; padding: 0.75rem; border-radius: 0.5rem; max-width: 90%; word-break: break-word; line-height: 1.6; }
.user-message {
background-color: rgba(var(--user-message-rgb), 0.8)!important;
color: rgba(var(--user-text-rgb), 0.9)!important;
align-self: flex-end;
margin-left: 10%;
border: 1px solid rgba(var(--user-message-rgb), 0.9);
}
.ai-message {
background-color: rgba(var(--ai-message-rgb), 0.8)!important;
color: rgba(var(--ai-text-rgb), 0.9)!important;
align-self: flex-start;
margin-right: 10%;
white-space: pre-wrap;
border: 1px solid rgba(var(--ai-message-rgb), 0.9);}
.ai-message .response-content p { margin-bottom: 0.5em; } /* Add some space between paragraphs from Markdown */
.ai-message .response-content ul, .ai-message .response-content ol { margin-left: 1.5em; margin-bottom: 0.5em; }
.ai-message .response-content li { margin-bottom: 0.25em; }
.ai-message img { display: block; max-width: 100%; max-height: 300px; height: auto; margin-top: 0.75rem; border-radius: 0.375rem; background-color: #4b5563; } /* Adjusted max-height for mobile */
.ai-message strong, .user-message strong { display: block; margin-bottom: 0.25rem; font-weight: bold; color: #9ca3af; }
.ai-message .response-content strong { font-weight: bold; color: inherit; }
.error-message { background-color: #b91c1c; color: white; }
.loader { border: 4px solid #f3f3f3; border-top: 4px solid #3498db; border-radius: 50%; width: 20px; height: 20px; animation: spin 1s linear infinite; display: inline-block; margin-left: 8px; }
@keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }
textarea { scrollbar-width: thin; scrollbar-color: #4b5563 #374151; }
@keyframes breathe{0%{color:white;text-shadow:0 0 8px rgba(255,255,255,0.7);}50%{color:#22d3ee;text-shadow:0 0 12px rgba(34,211,238,0.9);}100%{color:white;text-shadow:0 0 8px rgba(255,255,255,0.7);}}.animate-breathe{animation:breathe 3s ease-in-out infinite;}
.ai-message table {
border-collapse: collapse;
width: 98%;
margin: 1em auto;
background: rgba(var(--table-bg-rgb), 0.9)!important;
border: 1px solid rgba(var(--ai-message-rgb), 0.8);
box-shadow: 0 2px 5px rgba(0, 0, 0, 0.2);
}
.ai-message table { border: 1px solid rgba(var(--table-border-rgb), 0.8)!important;}
.ai-message th { background-color: rgba(var(--table-header-rgb), 0.9)!important;}
.ai-message tr:hover td { background-color: rgba(var(--table-hover-rgb), 0.4)!important;}
.ai-message th, .ai-message td {
border: 1px solid rgba(var(--ai-message-rgb), 0.8);
padding: 0.5rem 0.75rem;
text-align: left;
background: transparent!important;
}
.ai-message th {
background-color: rgba(var(--table-header-rgb), 0.9)!important;
color: #E2E8F0;
font-weight: bold;
}
/* 移除交替行颜色 */
.ai-message tr {
background: transparent!important;
}
/* 表格悬停效果 */
.ai-message tr:hover td {
background-color: rgba(74, 85, 104, 0.3)!important;
}
/* 确保表格内的strong不显示图标 */
.ai-message table strong::before {
display: none!important;
}
#chat > div {
transition: all 0.3s ease;
box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}
#chat > div:hover {
transform: scale(1.02);
box-shadow: 0 4px 15px rgba(0, 0, 0, 0.3);
z-index: 1;
}
/* 彩虹呼吸主题专用动画 */
@keyframes rainbowBreath {
0% { filter: hue-rotate(0deg); opacity: 0.8; }
50% { filter: hue-rotate(180deg); opacity: 0.95; }
100% { filter: hue-rotate(360deg); opacity: 0.8; }
}
.rainbow-theme {
animation: rainbowBreath 8s ease-in-out infinite;
background: linear-gradient(45deg,
rgba(25,25,25,0.75) 0%,
rgba(255,0,0,0.8) 20%,
rgba(255,165,0,0.75) 40%,
rgba(255,255,0,0.8) 60%,
rgba(0,255,0,0.75) 80%,
rgba(0,0,255,0.8) 100%);
background-size: 200% 200%;
animation: rainbowBreath 20s ease-in-out infinite; /* 底图 */
}
/* 聊天气泡单独控制 */
#chat > div.rainbow-theme {
animation: rainbowBreath 20s ease-in-out infinite; /* 气泡 */
opacity: 0.9;
filter: none; /* 移除hue-rotate避免颜色偏移 */
background: var(--ai-message-rgb); /* 使用主题色 */
border-color: rgba(255,255,255,0.5)!important;
}
</style>
`;
// Client-side JavaScript
const getClientScript = () => `
<script>
document.addEventListener('DOMContentLoaded', () => {
const themeConfig = {
pink: { // 少女粉
bg: '45,30,40', // 深粉紫背景(增强对比)
user: '255,105,180', // 亮粉用户消息(类似樱花粉)
ai: '220,130,170', // 柔和粉AI消息
input: '200,100,150', // 输入框背景(紫粉)
table: '180,80,130', // 表格背景(玫瑰粉)
tableHeader: '190,90,140', // 表头稍亮
tableHover: '230,150,180', // 悬停效果(浅粉)
tableBorder: '210,120,160', // 边框(粉紫)
error: '255,80,120', // 错误消息(亮粉红)
primary: '255,150,200', // 主色调(糖果粉)
userText: '255,240,245', // 用户消息文字(粉白)
aiText: '255,230,240', // AI消息文字(淡粉白)
linkText: '255,180,220' // 链接文字(浅粉)
},
default: {
bg: '20,42,58',
user: '30,144,200', //
ai: '50,110,140', //
input: '40,100,130', //
table: '35,90,120', //
error: '185,28,28',
primary: '0,150,200',
userText: '240,250,255',
aiText: '230,240,250',
linkText: '160,220,255'
},
purple: {
bg: '49,46,129',
user: '76,29,149',
ai: '76,29,149',
input: '76,29,149',
table: '76,29,149',
error: '134,25,143',
primary: '124,58,237',
userText: '245,243,255',
aiText: '245,243,255',
linkText: '216,180,254' },
green: {
bg: '6,78,59',
user: '5,150,105',
ai: '5,150,105',
input: '5,150,105',
table: '5,150,105',
error: '28,185,100',
primary: '16,185,129',
userText: '240,253,244',
aiText: '240,253,244',
linkText: '167,243,208' },
cyberpunk: {
bg: '17,24,39',
user: '63,114,175',
ai: '88,28,135',
input: '28,28,40',
table: '28,100,138',
tableHeader: '15,82,87',
tableHover: '0,255,255',
tableBorder: '0,255,187',
error: '255,0,122',
primary: '0,255,187',
userText: '224,242,254',
aiText: '245,200,255',
linkText: '0,255,255' },
gradient: {
bg: '25,25,112',
user: '70,130,180',
ai: '147,112,219',
input: '106,90,205',
table: '72,61,139',
tableHeader: '123,104,238',
tableHover: '138,43,226',
tableBorder: '147,112,219',
error: '255,99,71',
primary: '255,140,0',
userText: '240,248,255',
aiText: '230,230,250',
linkText: '255,215,0' },
prism: {
bg: '10,10,30',
user: '255,105,180',
ai: '147,112,219',
input: '75,0,130',
table: '123,104,238',
tableHeader: '138,43,226',
tableHover: '148,0,211',
tableBorder: '255,20,147',
error: '255,0,0',
primary: '0,255,255',
userText: '255,255,255',
aiText: '255,215,0',
linkText: '255,20,147' },
rainbow: {
bg: '25,25,25',
user: '255,0,0',
ai: '0,255,0',
input: '0,0,255',
table: '255,255,0',
tableHeader: '255,0,255',
tableHover: '0,255,255',
tableBorder: '255,165,0',
error: '255,0,122',
primary: '148,0,211',
userText: '250,250,250',
aiText: '250,250,250',
linkText: '255,255,255'
}
};
const themeSelect = document.getElementById('theme');
function initTheme() {
themeSelect.addEventListener('change', (e) => {
console.log("Applying theme:", e.target.value);
applyTheme(e.target.value);
const currentScroll = chatContainer.scrollTop;
setTimeout(() => chatContainer.scrollTop = currentScroll, 0);
});
applyTheme(themeSelect.value); // 初始化主题
} initTheme();
"use strict";
// 新增主题切换函数
function applyTheme(themeName) {
const theme = themeConfig[themeName] || themeConfig.default;
document.documentElement.style.setProperty('--theme-bg-rgb', theme.bg);
document.documentElement.style.setProperty('--table-hover-rgb', theme.tableHover);
document.documentElement.style.setProperty('--table-border-rgb', theme.tableBorder);
document.documentElement.style.setProperty('--input-border-rgb', theme.input);
document.documentElement.style.setProperty('--table-header-rgb', theme.tableHeader);
document.documentElement.style.setProperty('--user-message-rgb', theme.user);
document.documentElement.style.setProperty('--ai-message-rgb', theme.ai);
document.documentElement.style.setProperty('--input-bg-rgb', theme.input);
document.documentElement.style.setProperty('--table-bg-rgb', theme.table);
document.documentElement.style.setProperty('--table-header-rgb', theme.table);
document.documentElement.style.setProperty('--error-message-rgb', theme.error);
document.documentElement.style.setProperty('--theme-primary-rgb', theme.primary);
document.documentElement.style.setProperty('--user-text-rgb', theme.userText);
document.documentElement.style.setProperty('--ai-text-rgb', theme.aiText);
document.documentElement.style.setProperty('--link-text-rgb', theme.linkText);
// 处理特殊主题的样式覆盖
const isCyberpunk = themeName === 'cyberpunk';
document.body.classList.toggle('rainbow-theme', themeName === 'rainbow');
document.querySelectorAll('#chat > div').forEach(el => {
el.classList.toggle('rainbow-theme', themeName === 'rainbow');
});
document.querySelectorAll('select, #sendBtn').forEach(el => {
el.style.borderColor = isCyberpunk ? 'rgba(0,255,187,0.8)' : 'rgba(var(--input-border-rgb),0.5)';
el.style.backgroundColor = isCyberpunk ? 'rgba(28,28,40,0.9)' : 'rgba(var(--input-bg-rgb),0.5)';
});
}
"use strict";
console.log("DOM fully loaded and parsed.");
const chat = document.getElementById('chat');
const chatContainer = document.getElementById('chat-container');
const sendBtn = document.getElementById('sendBtn');
const promptTextarea = document.getElementById('prompt');
const modelSelect = document.getElementById('model');
const sendIcon = document.getElementById('sendIcon');
const loadingIcon = document.getElementById('loadingIcon');
const buttonText = sendBtn ? sendBtn.querySelector('.button-text') : null;
if (!chat || !chatContainer || !sendBtn || !promptTextarea || !modelSelect || !sendIcon || !loadingIcon || !buttonText) {
console.error("CRITICAL ERROR: One or more essential HTML elements not found.");
alert("页面加载错误:无法找到必要的聊天界面元素。请检查HTML结构或稍后重试。");
return;
}
console.log("All essential elements found.");
function setLoadingState(isLoading) {
console.log(\`setLoadingState called with isLoading: \${isLoading}\`);
if (!sendBtn || !promptTextarea || !buttonText || !sendIcon || !loadingIcon) {
console.error("Error inside setLoadingState: Required elements missing.");
return;
}
try {
sendBtn.disabled = isLoading;
promptTextarea.disabled = isLoading;
buttonText.textContent = isLoading ? "处理中..." : "发送(Post)";
sendIcon.classList.toggle('hidden', isLoading);
loadingIcon.classList.toggle('hidden', !isLoading);
console.log("setLoadingState finished.");
} catch (e) { console.error("Error executing setLoadingState:", e); }
}
function spawnThinkingIcon() {
const icon = document.createElement('img');
icon.src = 'https://i.ibb.co/ch21FSqt/cf.png';
icon.className = 'thinking-icon';
document.body.appendChild(icon);
icon.addEventListener('animationend', function() { icon.remove(); });
}
function addMessage(text, sender = 'ai', isLoading = false) {
console.log('addMessage called. Sender: ' + sender + ', isLoading: ' + isLoading);
if (!chat || !modelSelect) { console.error("Error inside addMessage: Chat or modelSelect element not found."); return null; }
try {
let messageDiv = document.createElement('div');
messageDiv.classList.add(sender === 'user' ? 'user-message' : 'ai-message');
const senderStrong = document.createElement('strong');
senderStrong.textContent = sender === 'user' ? '你:' : 'Gemini-AI:';
messageDiv.appendChild(senderStrong);
const contentSpan = document.createElement('span');
contentSpan.className = 'response-content';
if (isLoading) {
const thinkingSpan = document.createElement('span');
thinkingSpan.className = 'thinking';
thinkingSpan.textContent = ' 深度思考中(Deep Reasoning)...';
messageDiv.appendChild(thinkingSpan);
messageDiv.appendChild(contentSpan); // Add empty contentSpan for placeholder
spawnThinkingIcon();
} else {
if (sender === 'user') {
contentSpan.textContent = text; // User messages are plain text
} else {
// For AI messages, parse Markdown if marked.js is available
if (modelSelect.value.startsWith('imagen') && (text.includes('<img') || text.includes('data:image'))) {
contentSpan.innerHTML = text; // Imagen response might already be HTML (img tags)
} else if (typeof marked !== 'undefined') {
contentSpan.innerHTML = marked.parse(text); // Parse Markdown to HTML
} else {
contentSpan.textContent = text; // Fallback if marked.js is not loaded
}
}
messageDiv.appendChild(contentSpan);
}
chat.appendChild(messageDiv);
console.log("Message added to chat.");
scrollToBottom();
return messageDiv;
} catch (e) { console.error("Error executing addMessage:", e); return null; }
}
function scrollToBottom() {
try {
if (chatContainer) { chatContainer.scrollTop = chatContainer.scrollHeight; }
else { console.error("Error scrolling: chatContainer not found."); }
} catch (e) { console.error("Error executing scrollToBottom:", e); }
}
function escapeHTML(str) { // Keep this for cases where you might need to escape HTML, though not used for AI response directly now
if (typeof str !== 'string') return '';
const p = document.createElement('p');
p.appendChild(document.createTextNode(str));
return p.innerHTML;
}
function autoResizeTextarea() {
try {
if (promptTextarea) {
promptTextarea.style.height = 'auto';
promptTextarea.style.height = Math.min(promptTextarea.scrollHeight, 200) + 'px'; // Max height 200px
} else { console.error("Error resizing textarea: promptTextarea not found.");}
} catch (e) { console.error("Error executing autoResizeTextarea:", e); }
}
async function handleSend() {
console.log("handleSend function started.");
console.log("Button click detected");
let aiMessageDiv = null;
let responseContentSpan = null;
try {
const prompt = promptTextarea.value.trim();
const model = modelSelect.value;
if (!prompt) { alert("请输入你的内容或画面描述!"); promptTextarea.focus(); return; }
setLoadingState(true);
addMessage(prompt, 'user');
promptTextarea.value = '';
autoResizeTextarea();
aiMessageDiv = addMessage('', 'ai', true);
if (!aiMessageDiv) { throw new Error("Failed to create AI placeholder message element."); }
responseContentSpan = aiMessageDiv.querySelector('.response-content');
const thinkingSpan = aiMessageDiv.querySelector('.thinking');
if (!responseContentSpan) { throw new Error("Failed to find response content span in AI placeholder."); }
const res = await fetch(location.href, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ prompt, model })
});
console.log(\`Worker response received. Status: \${res.status}, ok: \${res.ok}\`);
if (thinkingSpan) thinkingSpan.remove();
if (!res.ok) {
const errorText = await res.text();
console.error(\`Worker/API Error Response (Status \${res.status}):\`, errorText);
if (responseContentSpan && aiMessageDiv) {
// For error messages, we might want to display them as plain text or escaped HTML
// to avoid them being misinterpreted as Markdown.
responseContentSpan.textContent = \`请求出错 (\${res.status}): \${escapeHTML(errorText.substring(0, 500))}\${errorText.length > 500 ? '...' : ''}\`;
aiMessageDiv.classList.add('error-message');
scrollToBottom();
} else { console.error("Cannot display fetch error in chat: message elements not found."); }
throw new Error(\`Server responded with status \${res.status}\`);
}
const selectedModelType = model.startsWith("imagen") ? "imagen" : "gemini";
console.log(\`Handling response for model type: \${selectedModelType}\`);
if (selectedModelType === "gemini") {
console.log("Processing Gemini SSE stream...");
const reader = res.body.getReader();
const decoder = new TextDecoder();
let buffer = '';
let currentText = '';
// eslint-disable-next-line no-constant-condition
while (true) {
const { done, value } = await reader.read();
if (done) { console.log("SSE stream finished."); break; }
buffer += decoder.decode(value, { stream: true });
const lines = buffer.split('\\n');
buffer = lines.pop(); // Keep potential partial line for next read
for (const line of lines) {
if (line.startsWith('data: ')) {
const jsonStr = line.substring(6).trim();
if (jsonStr === '[DONE]' || !jsonStr) continue;
try {
const chunk = JSON.parse(jsonStr);
const textPart = chunk.candidates?.[0]?.content?.parts?.[0]?.text;
if (textPart) {
currentText += textPart;
// Parse and render Markdown progressively
if (typeof marked !== 'undefined') {
responseContentSpan.innerHTML = marked.parse(currentText);
} else {
responseContentSpan.textContent = currentText; // Fallback
}
scrollToBottom();
} else if (chunk.promptFeedback?.blockReason) {
const blockMessage = \`\\n[内容被阻止: \${chunk.promptFeedback.blockReason}]\`;
currentText += blockMessage;
if (typeof marked !== 'undefined') {
responseContentSpan.innerHTML = marked.parse(currentText);
} else {
responseContentSpan.textContent = currentText; // Fallback
}
aiMessageDiv.classList.add('error-message'); // Style as error
scrollToBottom();
}
} catch (e) {
console.error("Error parsing streaming JSON chunk:", e, "Chunk:", jsonStr);
const parseErrorMessage = '\\n[解析数据块时出错]';
currentText += parseErrorMessage;
if (typeof marked !== 'undefined') {
responseContentSpan.innerHTML = marked.parse(currentText);
} else {
responseContentSpan.textContent = currentText; // Fallback
}
scrollToBottom();
}
} else if (line.trim()) { console.log("Received non-data SSE line:", line); }
}
}
// Process any remaining data in the buffer after the stream ends
if (buffer.trim() && buffer.startsWith('data: ')) {
const jsonStr = buffer.substring(6).trim();
try {
const chunk = JSON.parse(jsonStr);
const textPart = chunk.candidates?.[0]?.content?.parts?.[0]?.text;
if (textPart) {
currentText += textPart;
if (typeof marked !== 'undefined') {
responseContentSpan.innerHTML = marked.parse(currentText);
} else {
responseContentSpan.textContent = currentText; // Fallback
}
scrollToBottom();
}
} catch (e) {
console.error("Error parsing final buffer:", e);
const finalBufferError = '\\n[处理流末尾数据时出错]';
currentText += finalBufferError;
if (typeof marked !== 'undefined') {
responseContentSpan.innerHTML = marked.parse(currentText);
} else {
responseContentSpan.textContent = currentText; // Fallback
}
scrollToBottom();
}
}
} else if (selectedModelType === "imagen") {
console.log("Processing Imagen JSON response...");
try {
const data = await res.json();
console.log("Imagen response JSON parsed:", data);
if (data.images && data.images.length > 0) {
// Imagen response is typically direct HTML (img tags)
responseContentSpan.innerHTML = data.images.map((imgSrc, index) => \`<img src="\${imgSrc}" class="my-2 rounded shadow-md" alt="Generated image \${index + 1}" loading="lazy"/>\`).join('');
} else {
const message = data.message || (data.promptFeedback?.blockReason ? \`请求被阻止: \${data.promptFeedback.blockReason}\` : "未生成任何图像或收到意外响应。");
responseContentSpan.textContent = escapeHTML(message); // Display as plain text
if (message.includes("Blocked") || message.includes("Error") || message.includes("出错") || message.includes("Unexpected") || message.includes("阻止")) {
aiMessageDiv.classList.add('error-message');
}
}
scrollToBottom();
} catch (e) {
console.error("Error parsing Imagen JSON response:", e);
if(responseContentSpan && aiMessageDiv){
responseContentSpan.textContent = '解析图像响应时出错:' + e.message; // Display as plain text
aiMessageDiv.classList.add('error-message');
scrollToBottom();
}
throw new Error('Failed to parse Imagen JSON: ' + e.message);
}
console.log("Imagen JSON processing finished.");
}
console.log("handleSend processing completed successfully.");
} catch (error) {
console.error("!!!! CLIENT-SIDE CATCH BLOCK ERROR in handleSend !!!!:", error);
if (responseContentSpan) {
if (!responseContentSpan.textContent.includes("出错")) {
responseContentSpan.textContent = '客户端错误: ' + error.message; // Display as plain text
}
if (aiMessageDiv && !aiMessageDiv.classList.contains('error-message')) {
aiMessageDiv.classList.add('error-message');
}
scrollToBottom();
} else { console.error("Cannot display error in chat bubble: responseContentSpan not found."); }
} finally {
console.log("!!!! CLIENT-SIDE FINALLY BLOCK in handleSend !!!!");
setLoadingState(false);
promptTextarea.focus();
console.log("UI re-enabled.");
}
}
sendBtn.addEventListener('click', handleSend);
promptTextarea.addEventListener('keypress', (e) => { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); handleSend(); } });
promptTextarea.addEventListener('input', autoResizeTextarea);
autoResizeTextarea();
console.log("Event listeners attached and initial setup done.");
});
</script>
`;
// Main HTML structure
export function renderHTML() {
const styles = getStyles();
const clientScript = getClientScript();
return `<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>輕音Joy-AI公益站</title>
<link rel="icon" href="https://www.cloudflare.com/favicon.ico" type="image/x-icon">
<script src="https://cdn.tailwindcss.com"></script>
<script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script> ${styles}
</head>
<style>
a {color: rgba(var(--link-text-rgb), 0.9)!important;text-shadow: 0 2px 4px rgba(var(--link-text-rgb), 0.3);}
a:hover {color: rgba(var(--link-text-rgb), 1)!important;text-decoration: underline;}
</style>
<body class="bg-gray-900 text-gray-100 min-h-screen flex flex-col items-center p-4 font-sans">
<h1 class="text-3xl font-bold my-6 text-center">Ultra AI ☁ Cloudflare 輕音Joy-AI公益站</h1>
<a href="https://qyjoy.vip" target="_blank" class="text-center block font-bold cursor-pointer mb-6 animate-breathe" style="text-shadow:0 0 8px rgba(0,255,255,0.7);">抖音 | Bilibili | Youtube | 小红书 | 公众号: 輕音Joy</a>
<div class="w-full max-w-6xl bg-gray-800 shadow-lg rounded-lg p-6 transition-colors duration-300">
<div class="flex flex-row gap-4 mb-4">
<div class="w-1/2">
<label for="model" class="block mb-2 text-sm font-medium text-gray-300">选择模型 Choose A Model:</label>
<select id="model" class="w-full p-2.5 rounded border border-gray-600/50 text-white focus:ring-blue-500 focus:border-blue-500" style="background:rgba(var(--input-bg-rgb),0.5)">
<option value="gemini-2.5-flash-preview-04-17">Gemini 2.5 Pro Preview</option>
</select>
</div>
<div class="w-1/2">
<label for="theme" class="block mb-2 text-sm font-medium text-gray-300">主题颜色 Theme color:</label>
<select id="theme" class="w-full p-2.5 rounded border border-gray-600/50 text-white">
<option value="default">默认色 Default Color</option>
<option value="purple">梦幻紫 Dreamy Purple</option>
<option value="green">自然绿 Natural Green</option>
<option value="pink">少女粉 Soft Pink</option>
<option value="cyberpunk">赛博霓虹 Cyberpunk Neon</option>
<option value="gradient">渐变紫橙 Gradient Purple-Orange</option>
<option value="prism">幻彩棱镜 Iridescent Prism</option>
<option value="rainbow">彩虹呼吸 Rainbow Breathing</option>
</select>
</div>
</div>
<div class="mb-4">
<label for="prompt" class="block mb-2 text-sm font-medium text-gray-300">输入你的任意问题 <br> (Input whatever you want):</label>
<textarea id="prompt" rows="3" class="w-full p-2.5 rounded bg-gray-700 border border-gray-600/50 text-white focus:ring-blue-500 focus:border-blue-500 resize-y" placeholder="例如:列表比较云计算、雾计算和边缘计算 或 列表格比较串行计算和并行计算 (Input whatever you want here...)" style="backdrop-filter:blur(4px)"></textarea>
</div>
<button id="sendBtn" class="flex items-center justify-center gap-2 w-full p-3 rounded font-semibold text-white/90 transition duration-150 ease-in-out disabled:opacity-50 disabled:cursor-not-allowed" style="background:rgba(37,99,235,0.75)!important;border:1px solid rgba(255,255,255,0.8)!important;backdrop-filter:blur(8px);box-shadow:0 2px 8px rgba(0,0,0,0.1)">
<img src="https://www.cloudflare.com/favicon.ico" alt="Cloudflare" class="w-4 h-4"><span class="button-text">发送 Post</span><span id="sendIcon">➤</span><span id="loadingIcon" class="loader hidden"></span>
</button>
<div id="chat-container" class="mt-6 border-t border-gray-700 pt-4">
<div id="chat" class="flex flex-col space-y-4">
<div class="ai-message"><strong>AI:</strong>你好!请选择一个模型并输入任意问题😀<br><br>Hi! Get started by selecting any models and input whatever you want!</div>
</div>
</div>
<p class="text-yellow-300 font-bold mt-4 mb-2 text-center text-sm">Powered By Cloudflare ☁ Serverless | © 2025 輕音Joy</p>
</div>
<footer class="text-center text-gray-500 text-sm mt-8 pb-4"></footer>
${clientScript}
</body>
</html>`;
}
================================================
FILE: V3(stable)/request-handler.js
================================================
// request-handler.js
// Handles incoming requests, routing, and basic validation.
import { renderHTML } from './html-renderer.js';
import { handleApiCall } from './api-handler.js';
import { corsHeaders } from './utils.js';
export async function handleRequest(request, env, ctx, logPrefix) {
// --- API Key Check ---
const GEMINI_API_KEY = env.GEMINI_API_KEY;
if (!GEMINI_API_KEY || GEMINI_API_KEY.length < 30) {
console.error(`${logPrefix} CRITICAL ERROR: API Key 未配置或无效`);
return new Response("Server Configuration Error: Invalid API Key.", {
status: 500,
headers: { "Content-Type": "text/plain; charset=utf-8", ...corsHeaders() }
});
}
// --- CORS Preflight ---
if (request.method === "OPTIONS") {
console.log(`${logPrefix} Responding to OPTIONS request.`);
return new Response(null, { status: 204, headers: corsHeaders() });
}
// --- Serve HTML for GET ---
if (request.method === "GET") {
console.log(`${logPrefix} Responding to GET request with HTML.`);
try {
const html = renderHTML();
return new Response(html, {
headers: { "Content-Type": "text/html; charset=utf-8", ...corsHeaders() },
});
} catch (e) {
console.error(`${logPrefix} Error rendering HTML:`, e);
return new Response("Internal Server Error rendering page.", { status: 500, headers: corsHeaders() });
}
}
// --- Handle POST for API calls ---
if (request.method === "POST") {
return handleApiCall(request, env, logPrefix);
}
// --- Method Not Allowed ---
console.log(`${logPrefix} Method Not Allowed: ${request.method}`);
return new Response("Method Not Allowed", {
status: 405,
headers: { "Allow": "GET, POST, OPTIONS", ...corsHeaders() }
});
}
================================================
FILE: V3(stable)/utils.js
================================================
// utils.js
// Utility functions for the worker.
export function corsHeaders() {
return {
"Access-Control-Allow-Origin": "*", // WARNING: Restrict this in production for security
"Access-Control-Allow-Methods": "GET, POST, OPTIONS",
"Access-Control-Allow-Headers": "Content-Type, Authorization", // Added Authorization as an example, include any other custom headers
};
}
================================================
FILE: V3(stable)/worker.js
================================================
// worker.js
// Main entry point for the Cloudflare Worker.
import { handleRequest } from './request-handler.js';
export default {
async fetch(request, env, ctx) {
// Assign a unique ID for request tracing
const requestId = request.headers.get('cf-ray') || crypto.randomUUID();
const logPrefix = `[${requestId}]`;
console.log(`${logPrefix} Worker received request: ${request.method} ${request.url}`);
// Delegate to the request handler
return handleRequest(request, env, ctx, logPrefix);
}
};
================================================
FILE: V4 EX(For mobile support Expand)/api-handler.js
================================================
import { corsHeaders } from './utils.js';
export async function handleApiCall(request, env, logPrefix) {
console.log(logPrefix + " Processing POST request for API call.");
let requestBody;
try {
requestBody = await request.json();
console.log(logPrefix + " Parsed request body. Model: " + requestBody?.model);
} catch (e) {
console.error(logPrefix + " Invalid JSON body received:", e);
return new Response("Invalid JSON body.", {
status: 400, headers: { "Content-Type": "text/plain; charset=utf-8", ...corsHeaders() }
});
}
const { model, history, currentTurnParts, customApiKey } = requestBody;
if (!model || !currentTurnParts || !Array.isArray(currentTurnParts)) {
console.error(logPrefix + " Missing model or currentTurnParts in request body.");
return new Response("Missing model or currentTurnParts in request body.", {
status: 400, headers: { "Content-Type": "text/plain; charset=utf-8", ...corsHeaders() }
});
}
const allowedModels = [
"gemini-2.0-flash",
"gemini-2.5-flash-preview-05-20",
"gemini-2.5-pro-preview-06-05",
"gemini-2.0-flash-preview-image-generation",
"veo-2.0-generate-001"
];
if (!allowedModels.includes(model)) {
console.error(logPrefix + " Invalid model selected: " + model);
return new Response("Invalid model selected: " + model + ". Allowed: " + allowedModels.join(", "), {
status: 400, headers: { "Content-Type": "text/plain; charset=utf-8", ...corsHeaders() }
});
}
const GEMINI_API_KEY = customApiKey || env.GEMINI_API_KEY;
if (!GEMINI_API_KEY) {
console.error(logPrefix + " CRITICAL ERROR: API Key not available (neither custom nor server default).");
return new Response("Server Configuration Error: API Key not available.", {
status: 500, headers: { "Content-Type": "text/plain; charset=utf-8", ...corsHeaders() }
});
}
let apiEndpoint = "streamGenerateContent";
let isStreaming = true;
if (model === "gemini-2.0-flash-preview-image-generation") {
apiEndpoint = "generateContent";
isStreaming = false;
} else if (model === "veo-2.0-generate-001") {
apiEndpoint = "generateVideo";
isStreaming = false;
}
const apiVersion = "v1beta";
const apiUrl = `https://generativelanguage.googleapis.com/${apiVersion}/models/${model}:${apiEndpoint}?key=${GEMINI_API_KEY}` + (isStreaming ? "&alt=sse" : "");
console.log(logPrefix + " Target API URL: " + apiUrl);
const contentsForApi = [];
if (history && Array.isArray(history)) {
history.forEach(turn => {
if (turn.role && turn.parts) {
contentsForApi.push({ role: turn.role, parts: turn.parts });
}
});
}
const systemPrompt = "answer in 中文"; // 这里可以根据需要修改提示词 you can set your own prompt here
let promptedUserParts = [...currentTurnParts];
if (promptedUserParts.length > 0 && typeof promptedUserParts[0].text === 'string') {
promptedUserParts[0] = { ...promptedUserParts[0], text: systemPrompt + " " + promptedUserParts[0].text };
} else {
promptedUserParts.unshift({ text: systemPrompt });
}
contentsForApi.push({ role: "user", parts: promptedUserParts });
const apiRequestBody = {contents: contentsForApi,};
try {
console.log(logPrefix + " Sending request to Google API...");
const apiResponse = await fetch(apiUrl, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(apiRequestBody)
});
console.log(logPrefix + " Google API response status: " + apiResponse.status + ", ok: " + apiResponse.ok);
if (!apiResponse.ok) {
const errorBodyText = await apiResponse.text();
console.error(logPrefix + " Google API Error (" + apiResponse.status + "): " + errorBodyText);
let userFriendlyError = "Google API Error (" + apiResponse.status + ")";
try {
const errorJson = JSON.parse(errorBodyText);
if (errorJson.error && errorJson.error.message) {
userFriendlyError += ": " + errorJson.error.message;
} else {
userFriendlyError += ": " + errorBodyText.substring(0, 200) + (errorBodyText.length > 200 ? "..." : "");
}
} catch (e) {
userFriendlyError += ": " + errorBodyText.substring(0, 200) + (errorBodyText.length > 200 ? "..." : "");
}
return new Response(userFriendlyError, {
status: apiResponse.status, headers: { "Content-Type": "text/plain; charset=utf-8", ...corsHeaders() }
});
}
console.log(logPrefix + " Streaming Gemini response back to client.");
const { readable, writable } = new TransformStream();
apiResponse.body.pipeTo(writable).catch(err => {
console.error(logPrefix + " Error piping Gemini stream:", err);
});
const responseHeaders = new Headers({
"Content-Type": "text/event-stream; charset=utf-8",
"Cache-Control": "no-cache",
"Connection": "keep-alive",
...corsHeaders()
});
return new Response(readable, { status: 200, headers: responseHeaders });
} catch (error) {
console.error(logPrefix + " Worker fetch error calling Google API:", error);
const errorMsg = "Internal Server Error calling Google API: " + error.message;
return new Response(errorMsg, {
status: 500, headers: { "Content-Type": "text/plain; charset=utf-8", ...corsHeaders() }
});
}
}
================================================
FILE: V4 EX(For mobile support Expand)/html-renderer.js
================================================
const getStyles = () => `
<style>
#video-bg {position: fixed;right: 0;bottom: 0;min-width: 100%;min-height: 100%;z-index: -1;object-fit: cover;}
:root {
--table-bg-rgb: 0, 0, 0;
--error-message-rgb: 185, 28, 28;
--user-text-rgb: 255, 255, 255;
--ai-text-rgb: 255, 255, 255;
--link-text-rgb: 199, 210, 254;
--theme-primary-rgb: 29, 78, 216;
--table-hover-rgb: 74, 85, 104;
--input-border-rgb: 55, 65, 81;
--table-border-rgb: 55, 65, 81;
--table-header-rgb: 30, 41, 59;
--input-bar-bg-rgb: 17, 24, 39;
}
html, body { height: 100vh;margin: 0; padding: 0; overflow: hidden;}
body {background: url('https://img.picui.cn/free/2025/05/17/6828a34e93555.png') no-repeat center center fixed;background-size: cover; display: flex; flex-direction: column;}
.main-content-area {backdrop-filter: blur(2px); flex-grow: 1; display: flex; flex-direction: column; width: 100%; overflow: hidden;}
#chat-container { flex: 1 1 auto; overflow-y: auto; scrollbar-width: thin; scrollbar-color: #4b5563 #374151; padding: 0.5rem 1rem; height: calc(100vh - 170px); }
#chat > div {background-color: rgba(var(--user-message-rgb), 0.8);}
.ai-message { background-color: rgba(var(--ai-message-rgb), 0.8);}
#prompt, #sendBtn, #clearChatBtn, #settingsBtn, #fileUploadBtn, #customApiKey, #saveApiKeyBtn, #setBgBtn, select { background-color: rgba(var(--input-bg-rgb), 0.5)!important; border-color: rgba(var(--input-border-rgb), 0.7) !important;}
#sendBtn:hover { background-color: rgba(var(--theme-primary-rgb), 0.6)!important;}
.input-bar-container {
position: fixed;
bottom: 0;
left: 0;
width: 100%;
z-index: 1000;
background-color: rgba(var(--input-bar-bg-rgb), 0.9);
backdrop-filter: blur(2px);
padding: 0.2rem 0.2rem;
border-top: 1px solid rgba(var(--input-border-rgb), 0.7);
display: flex;
flex-direction: column;
box-shadow: 0 -2px 1px rgba(0,0,0,0.1);
}
.user-message {
background-color: rgba(var(--user-message-rgb), 0.8)!important;
color: rgba(var(--user-text-rgb), 0.9)!important;
align-self: flex-end;
margin-left: 3%;
border: 1px solid rgba(var(--user-message-rgb), 0.9);
position: relative;
}
.ai-message {
background-color: rgba(var(--ai-message-rgb), 0.8)!important;
color: rgba(var(--ai-text-rgb), 0.9)!important;
align-self: flex-start;
margin-right: 2%;
white-space: pre-wrap;
border: 1px solid rgba(var(--ai-message-rgb), 0.9);
}
#chat > div { margin-bottom: 0.2rem; padding: 0.25rem; border-radius: 0.5rem; max-width: 95%; word-break: break-word; line-height: 1.6; }
.ai-message > strong::before {content: "";display: inline-block;width: 20px;height: 20px;background-image: url('https://www.gstatic.com/lamda/images/sparkle_resting_v2_1ff6f6a71f2d298b1a31.gif');background-size: contain;background-repeat: no-repeat;margin-right: 8px;vertical-align: middle;}
.text-3xl{background:linear-gradient(45deg,red,orange,yellow,green,blue,purple,red);-webkit-background-clip:text;background-clip:text;color:transparent;background-size:500% auto;animation:rainbow 10s linear infinite}@keyframes rainbow{0%{background-position:0}300%{background-position:500%}}
@keyframes textGlow{0%{text-shadow:0 0 10px rgba(var(--theme-primary-rgb),.8),0 0 20px rgba(var(--theme-primary-rgb),.6);transform:scale(1)}50%{text-shadow:0 0 30px rgba(var(--theme-primary-rgb),.9),0 0 50px rgba(var(--theme-primary-rgb),.8),0 0 70px rgba(var(--theme-primary-rgb),.6);transform:scale(1.05)}100%{text-shadow:0 0 10px rgba(var(--theme-primary-rgb),.8),0 0 20px rgba(var(--theme-primary-rgb),.6);transform:scale(1)}}
.thinking{animation:textGlow 1.5s ease-in-out infinite;color:#a78bfa!important;font:italic bold 1.2em sans-serif}
@keyframes icon2DRotate {0% { opacity: 0; transform: scale(0) rotateY(0deg); } 10% { opacity: 1; transform: scale(3) rotateY(0deg); } 50% { transform: scale(3) rotateY(180deg); } 90% { transform: scale(3) rotateY(350deg); } 100% { opacity: 0; transform: scale(0) rotateY(360deg); }}
.thinking-icon {position: fixed; top: 40%; left: 50%;width: 80px; height: 80px; margin: -40px 0 0 -40px;pointer-events: none;animation: icon2DRotate 6s ease-in-out forwards;transform-origin: center center;transform-style: preserve-3d;filter: drop-shadow(0 0 25px #dba0ff) brightness(1.5) saturate(1.8);z-index: 9999;}
@media (min-width: 768px) {
#chat > div {
max-width: min(95%, 1200px);
padding: 1rem 1.25rem;
}
.user-message, .ai-message {
margin-left: 1%;
margin-right: 1%;
}
}
.ai-message .response-content p { margin-bottom: 0.5em; }
.ai-message .response-content ul, .ai-message .response-content ol { margin-left: 0.5em; margin-bottom: 0.5em; }
.ai-message .response-content li { margin-bottom: 0.25em; }
.ai-message img.generated-image { display: block; max-width: 100%; max-height: 300px; height: auto; margin-top: 0.75rem; border-radius: 0.375rem; background-color: #4b5563; }
.ai-message strong, .user-message strong { display: block; margin-bottom: 0.25rem; font-weight: bold; color: #9ca3af; }
.ai-message .response-content strong { font-weight: bold; color: inherit; }
.error-message { background-color: rgba(var(--error-message-rgb), 0.8) !important; color: white !important; }
.loader { border: 4px solid #f3f3f3; border-top: 4px solid #3498db; border-radius: 50%; width: 20px; height: 20px; animation: spin 1s linear infinite; display: inline-block; }
@keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }
textarea#prompt { scrollbar-width: thin; scrollbar-color: #4b5563 #374151; min-height: 42px; /* Match button height */ line-height: 1.5; resize: none;}
@keyframes breathe{0%{color:white;text-shadow:0 0 8px rgba(255,255,255,0.7);}50%{color:#22d3ee;text-shadow:0 0 12px rgba(34,211,238,0.9);}100%{color:white;text-shadow:0 0 8px rgba(255,255,255,0.7);}}.animate-breathe{animation:breathe 3s ease-in-out infinite;}
.ai-message table {
border-collapse: collapse;
width: 98%;
margin: 1em auto;
background: rgba(var(--table-bg-rgb), 0.9)!important;
border: 1px solid rgba(var(--table-border-rgb), 0.8)!important;
box-shadow: 0 2px 5px rgba(0, 0, 0, 0.2);
}
.ai-message th { background-color: rgba(var(--table-header-rgb), 0.9)!important; color: #E2E8F0; font-weight: bold;}
.ai-message tr:hover td { background-color: rgba(var(--table-hover-rgb), 0.4)!important;}
.ai-message th, .ai-message td {
border: 1px solid rgba(var(--table-border-rgb), 0.8);
padding: 0.5rem 0.75rem;
text-align: left;
background: transparent!important;
}
.ai-message tr { background: transparent!important; }
.ai-message table strong::before { display: none!important; }
#chat > div {
transition: all 0.3s ease;
box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}
#chat > div:hover {
transform: scale(1.01); /* Subtle hover */
box-shadow: 0 4px 10px rgba(0, 0, 0, 0.2);
z-index: 10;
}
/* Edit pencil button */
.edit-prompt-btn {
position: absolute;
bottom: 5px;
right: 5px;
background: rgba(100,100,100,0.5);
color: white;
border: none;
border-radius: 50%;
width: 24px;
height: 24px;
font-size: 14px;
cursor: pointer;
display: none; /* Hidden by default */
opacity: 0.7;
transition: opacity 0.2s;
line-height: 24px; text-align: center;
}
.user-message:hover .edit-prompt-btn { display: inline-block; }
.edit-prompt-btn:hover { opacity: 1; }
/* File preview */
.file-preview-badge {
display: inline-block;
background-color: rgba(var(--theme-primary-rgb), 0.7);
color: white;
padding: 2px 8px;
border-radius: 12px;
font-size: 0.8em;
margin-right: 3px;
margin-bottom: 3px;
}
.file-preview-badge .remove-file {
margin-left: 3px;
cursor: pointer;
font-weight: bold;
}
.input-bar-container {position: fixed;bottom: 0;left: 0;right: 0;}
#filePreviews { box-shadow: none !important; border: none !important; }
#filePreviews.has-files { box-shadow: none !important; border: none !important; }
.video-preview-badge {display: inline-block;background-color: rgba(var(--theme-primary-rgb), 0.6);color: white;padding: 2px 8px;border-radius: 12px;font-size: 0.8em;margin-right: 5px;margin-bottom: 5px;}
/* Rainbow Theme Specifics */
@keyframes rainbowBreath {
0% { background-position: 0% 50%; filter: hue-rotate(0deg); opacity: 0.8; }
50% { background-position: 100% 50%; filter: hue-rotate(180deg); opacity: 0.95; }
100% { background-position: 0% 50%; filter: hue-rotate(360deg); opacity: 0.8; }
}
/* Main content area subtle rainbow background */
.rainbow-theme-bg {
animation: rainbowBreath 20s ease-in-out infinite !important;
background: linear-gradient(45deg, rgba(105,25,205,0.05) 0%, rgba(255,0,0,0.05) 15%, rgba(255,165,0,0.05) 30%, rgba(255,255,0,0.05) 45%, rgba(0,255,0,0.05) 60%, rgba(0,0,255,0.05) 75%, rgba(75,0,130,0.05) 90%, rgba(255,211,255,0.05) 100%) !important;
background-size: 300% 300% !important;
}
/* Chat bubbles for rainbow theme */
.user-message.rainbow-theme-bubble {
border-color: rgba(255,255,255,0.5) !important;
animation: rainbowBreath 9s linear infinite !important;
background: linear-gradient(60deg,
rgba(0,0,255,0.5) 0%, /* Blue */
rgba(75,0,130,0.5) 20%, /* Indigo */
rgba(255,0,0,0.5) 40%, /* Red */
rgba(255,165,0,0.5) 60%, /* Orange */
rgba(255,255,0,0.5) 80%, /* Yellow */
rgba(0,255,0,0.5) 100% /* Green */
) !important;
background-size: 300% 300% !important;
color: white !important;
}
.ai-message.rainbow-theme-bubble {
border-color: rgba(255,255,255,0.5)!important;
animation: rainbowBreath 8s linear infinite !important;
background: linear-gradient(45deg,
rgba(255, 211, 255, 0.5) 0%, /* Pinkish */
rgba(255,165,0,0.5) 20%, /* Orange */
rgba(255,255,0,0.5) 40%, /* Yellow */
rgba(0,255,0,0.5) 60%, /* Green */
rgba(0,0,255,0.5) 80%, /* Blue */
rgba(148,0,211,0.5) 100% /* Violet */
) !important;
background-size: 300% 300% !important;
color: white !important;
}
.input-bar-container.rainbow-active #prompt,
.input-bar-container.rainbow-active #sendBtn,
.input-bar-container.rainbow-active #clearChatBtn,
.input-bar-container.rainbow-active #settingsBtn,
.input-bar-container.rainbow-active #fileUploadBtn,
.input-bar-container.rainbow-active #customApiKey,
.input-bar-container.rainbow-active #saveApiKeyBtn,
.input-bar-container.rainbow-active #setBgBtn,
.input-bar-container.rainbow-active select,
.input-bar-container.rainbow-active #filePreviews .file-preview-badge,
.input-bar-container.rainbow-active #filePreviews .video-preview-badge {
animation: rainbowBreath 8s linear infinite !important;
background: linear-gradient(45deg,
rgba(255, 211, 255, 0.7) 0%, /* Pinkish */
rgba(255,165,0,0.7) 15%, /* Orange */
rgba(255,255,0,0.7) 30%, /* Yellow */
rgba(0,255,0,0.7) 45%, /* Green */
rgba(0,0,255,0.7) 60%, /* Blue */
rgba(75,0,130,0.7) 75%, /* Indigo */
rgba(148,0,211,0.7) 90%, /* Purple */
rgba(255,211,255,0.7) 100% /* Loop back to Pinkish for smooth transition */
) !important;
background-size: 300% 300% !important;
border-color: rgba(255,255,255,0.6) !important;
color: white !important; /* Ensure text is visible */
text-shadow: 0 1px 2px rgba(0,0,0,0.3);
}
/* Hover effects for the buttons in the rainbow theme */
.input-bar-container.rainbow-active #sendBtn:hover,
.input-bar-container.rainbow-active #clearChatBtn:hover,
.input-bar-container.rainbow-active #settingsBtn:hover,
.input-bar-container.rainbow-active #fileUploadBtn:hover,
.input-bar-container.rainbow-active #saveApiKeyBtn:hover,
.input-bar-container.rainbow-active #setBgBtn:hover {
filter: brightness(1.2) saturate(1.2);
box-shadow: 0 0 10px rgba(255,255,255,0.4);
}
.input-bar-container.rainbow-active #prompt::placeholder,
.input-bar-container.rainbow-active #customApiKey::placeholder {
color: rgba(255, 255, 255, 0.7) !important;
opacity: 1;
}
.dragover-active {
border-color: rgba(var(--theme-primary-rgb), 0.9) !important;
box-shadow: 0 0 0 3px rgba(var(--theme-primary-rgb), 0.6) !important;
}
#fontSizeSlider {
-webkit-appearance: none;
appearance: none;
width: 100%; /* Full width within its container */
height: 8px;
background: rgba(var(--input-bg-rgb), 0.6);
border-radius: 5px;
outline: none;
opacity: 0.8;
transition: opacity .15s ease-in-out;
border: 1px solid rgba(var(--input-border-rgb), 0.7);
}
#fontSizeSlider:hover {
opacity: 1;
}
#fontSizeSlider::-webkit-slider-thumb {
-webkit-appearance: none;
appearance: none;
width: 18px;
height: 18px;
background: rgba(var(--theme-primary-rgb), 0.9);
border-radius: 50%;
cursor: pointer;
border: 2px solid rgba(255,255,255,0.6);
box-shadow: 0 0 5px rgba(var(--theme-primary-rgb),0.6);
}
#fontSizeSlider::-moz-range-thumb {
width: 18px;
height: 18px;
background: rgba(var(--theme-primary-rgb), 0.9);
border-radius: 50%;
cursor: pointer;
border: 2px solid rgba(255,255,255,0.6);
box-shadow: 0 0 5px rgba(var(--theme-primary-rgb),0.6);
}
.input-bar-container.rainbow-active #fontSizeSlider {
border-color: rgba(255,255,255,0.6) !important; /* Already covered by general rule but explicit for clarity */
}
.input-bar-container.rainbow-active #fontSizeSlider::-webkit-slider-thumb,
.input-bar-container.rainbow-active #fontSizeSlider::-moz-range-thumb {
/* Thumb will use the animated background from the general rule for .rainbow-active controls */
}
</style>
`;
const getClientScript = () => `
<script>
document.addEventListener('DOMContentLoaded', () => {
const themeConfig = {
pink: {
bg: '45,30,40', user: '255,105,180', ai: '220,130,170', input: '200,100,150', table: '180,80,130',
tableHeader: '190,90,140', tableHover: '230,150,180', tableBorder: '210,120,160', error: '255,80,120',
primary: '255,150,200', userText: '255,240,245', aiText: '255,230,240', linkText: '255,180,220',
inputBar: '30,20,30'
},
blue: {
bg: '20,42,58', user: '30,144,200', ai: '50,110,140', input: '40,100,130', table: '35,90,120',
tableHeader: '30,41,59', tableHover: '74,85,104', tableBorder: '55,65,81', error: '185,28,28',
primary: '0,150,200', userText: '240,250,255', aiText: '230,240,250', linkText: '160,220,255',
inputBar: '17,24,39'
},
purple: {
bg: '49,46,129', user: '76,29,149', ai: '76,29,149', input: '76,29,149', table: '76,29,149',
tableHeader: '60,20,120', tableHover: '90,40,160', tableBorder: '76,29,149', error: '134,25,143',
primary: '124,58,237', userText: '245,243,255', aiText: '245,243,255', linkText: '216,180,254',
inputBar: '30,25,80'
},
green: {
bg: '6,78,59', user: '5,150,105', ai: '5,150,105', input: '5,150,105', table: '5,150,105',
tableHeader: '4,120,80', tableHover: '10,170,120', tableBorder: '5,150,105', error: '28,185,100',
primary: '16,185,129', userText: '240,253,244', aiText: '240,253,244', linkText: '167,243,208',
inputBar: '3,60,40'
},
cyberpunk: {
bg: '17,24,39', user: '63,114,175', ai: '88,28,135', input: '28,28,40', table: '28,100,138',
tableHeader: '15,82,87', tableHover: '0,255,255', tableBorder: '0,255,187', error: '255,0,122',
primary: '0,255,187', userText: '224,242,254', aiText: '245,200,255', linkText: '0,255,255',
inputBar: '10,15,30'
},
gradient: {
bg: '25,25,112', user: '70,130,180', ai: '147,112,219', input: '106,90,205', table: '72,61,139',
tableHeader: '123,104,238', tableHover: '138,43,226', tableBorder: '147,112,219', error: '255,99,71',
primary: '255,140,0', userText: '240,248,255', aiText: '230,230,250', linkText: '255,215,0',
inputBar: '20,20,80'
},
prism: {
bg: '10,10,30', user: '255,105,180', ai: '147,112,219', input: '75,0,130', table: '123,104,238',
tableHeader: '138,43,226', tableHover: '148,0,211', tableBorder: '255,20,147', error: '255,0,0',
primary: '0,255,255', userText: '255,255,255', aiText: '255,215,0', linkText: '255,20,147',
inputBar: '5,5,20'
},
rainbow: {
bg: '20,20,20',
user: '255,0,0', ai: '0,255,0', input: '0,0,255', table: '255,255,0',
tableHeader: '255,0,255', tableHover: '0,255,255', tableBorder: '255,165,0',
error: '255,0,122', primary: '148,0,211', userText: '250,250,250',
aiText: '250,250,250', linkText: '255,255,255',
inputBar: '15,15,15'
},
red: {
bg: '255,245,245', user: '255,100,100', ai: '255,150,150', input: '255,200,200', table: '255,230,230',
tableHeader: '255,180,180', tableHover: '255,210,210', tableBorder: '255,160,160', error: '255,50,50',
primary: '255,80,80', userText: '50,0,0', aiText: '60,0,0', linkText: '220,0,0', inputBar: '255,235,235'
},
yellow: {
bg: '50,40,5', user: '255,215,50', ai: '240,200,40', input: '200,180,40', table: '150,130,30',
tableHeader: '170,150,35', tableHover: '230,210,80', tableBorder: '200,180,40', error: '255,100,0',
primary: '255,190,0', userText: '40,30,0', aiText: '40,30,0', linkText: '255,165,0',
inputBar: '40,35,10'
}
};
const themeSelect = document.getElementById('theme');
const mainContentArea = document.querySelector('.main-content-area');
const inputBarContainer = document.querySelector('.input-bar-container');
function applyTheme(themeName) {
const theme = themeConfig[themeName] || themeConfig.blue; // Fallback to blue (was default)
const root = document.documentElement;
root.style.setProperty('--theme-bg-rgb', theme.bg);
root.style.setProperty('--table-hover-rgb', theme.tableHover || themeConfig.blue.tableHover);
root.style.setProperty('--table-border-rgb', theme.tableBorder || themeConfig.blue.tableBorder);
root.style.setProperty('--input-border-rgb', theme.input);
root.style.setProperty('--table-header-rgb', theme.tableHeader || themeConfig.blue.tableHeader);
root.style.setProperty('--user-message-rgb', theme.user);
root.style.setProperty('--ai-message-rgb', theme.ai);
root.style.setProperty('--input-bg-rgb', theme.input);
root.style.setProperty('--table-bg-rgb', theme.table);
root.style.setProperty('--error-message-rgb', theme.error);
root.style.setProperty('--theme-primary-rgb', theme.primary);
root.style.setProperty('--user-text-rgb', theme.userText);
root.style.setProperty('--ai-text-rgb', theme.aiText);
root.style.setProperty('--link-text-rgb', theme.linkText);
root.style.setProperty('--input-bar-bg-rgb', theme.inputBar || themeConfig.blue.inputBar);
const isCyberpunk = themeName === 'cyberpunk';
const allInteractiveElements = document.querySelectorAll(
'select, #prompt, #sendBtn, #clearChatBtn, #settingsBtn, #fileUploadBtn, #customApiKey, #saveApiKeyBtn, #setBgBtn, #fontSizeSlider'
);
const textElementsInSettings = document.querySelectorAll('#apiKeyControls label, #fontSizeValue');
allInteractiveElements.forEach(el => {
// Clear any inline styles first, to let CSS classes take precedence or apply new theme's styles
el.style.borderColor = '';
el.style.backgroundColor = '';
if (themeName === 'rainbow') {
} else if (isCyberpunk) {
el.style.borderColor = 'rgba(0,255,187,0.8)';
el.style.backgroundColor = 'rgba(28,28,40,0.9)';
// Ensure text color for cyberpunk if not covered by general styles
if (el.tagName === 'SELECT' || el.id === 'prompt' || el.id === 'customApiKey') {
el.style.color = 'white';
}
} else { // Other themes (blue, pink, etc.)
el.style.borderColor = 'rgba(' + getComputedStyle(root).getPropertyValue('--input-border-rgb') + ',0.7)';
el.style.backgroundColor = 'rgba(' + getComputedStyle(root).getPropertyValue('--input-bg-rgb') + ',0.5)';
// Ensure text color for other themes if not covered (usually white by default)
if (el.tagName === 'SELECT' || el.id === 'prompt' || el.id === 'customApiKey') {
el.style.color = 'rgba(' + getComputedStyle(root).getPropertyValue('--user-text-rgb') + ',0.9)';
}
}
});
textElementsInSettings.forEach(el => {
if (themeName === 'rainbow') {
} else {
el.style.color = 'rgba(' + getComputedStyle(root).getPropertyValue('--user-text-rgb') + ',0.9)';
el.style.textShadow = '';
}
});
if (mainContentArea) {
mainContentArea.classList.toggle('rainbow-theme-bg', themeName === 'rainbow');
}
document.body.classList.remove('rainbow-theme-active');
if (inputBarContainer) {
inputBarContainer.classList.toggle('rainbow-active', themeName === 'rainbow');
}
document.querySelectorAll('#chat > div').forEach(el => {
el.style.backgroundColor = '';
if (themeName === 'rainbow') {
el.classList.add('rainbow-theme-bubble');
} else {
el.classList.remove('rainbow-theme-bubble');
// Reapply theme-specific bubble colors if not rainbow
if (el.classList.contains('user-message')) {
el.style.backgroundColor = 'rgba(' + getComputedStyle(root).getPropertyValue('--user-message-rgb') + ',0.8)';
} else if (el.classList.contains('ai-message')) {
el.style.backgroundColor = 'rgba(' + getComputedStyle(root).getPropertyValue('--ai-message-rgb') + ',0.8)';
}
}
});
}
function initTheme() {
themeSelect.value = 'rainbow';
applyTheme('rainbow');
themeSelect.addEventListener('change', (e) => {
applyTheme(e.target.value);
adjustMainContentPadding();
const currentScroll = chatContainer.scrollTop;
setTimeout(() => chatContainer.scrollTop = currentScroll, 0);
});
applyTheme('rainbow');
adjustMainContentPadding();
}
initTheme();
function adjustMainContentPadding() {
const inputBar = document.querySelector('.input-bar-container');
const mainArea = document.querySelector('.main-content-area');
const filePreviews = document.getElementById('filePreviews');
if (inputBar && mainArea) {
var inputBarHeight = inputBar.offsetHeight;
mainArea.style.paddingBottom = inputBarHeight + 'px';
if (filePreviews) { // Adjust file previews to sit above the input bar
filePreviews.style.bottom = (inputBarHeight + 1) + 'px';
}
}
}
"use strict";
console.log("DOM fully loaded and parsed.");
const chat = document.getElementById('chat');
const chatContainer = document.getElementById('chat-container');
const sendBtn = document.getElementById('sendBtn');
const promptTextarea = document.getElementById('prompt');
const modelSelect = document.getElementById('model');
const sendIcon = document.getElementById('sendIcon');
const loadingIcon = document.getElementById('loadingIcon');
const buttonText = sendBtn ? sendBtn.querySelector('.button-text') : null;
const clearChatBtn = document.getElementById('clearChatBtn');
const settingsBtn = document.getElementById('settingsBtn');
const customApiKeyInput = document.getElementById('customApiKey');
const saveApiKeyBtn = document.getElementById('saveApiKeyBtn');
const setBgBtn = document.getElementById('setBgBtn');
const bgFileInput = document.getElementById('bgFileInput');
const apiKeyControls = document.getElementById('apiKeyControls');
const fileUploadBtn = document.getElementById('fileUploadBtn');
const fileInput = document.getElementById('fileUpload');
const filePreviewsContainer = document.getElementById('filePreviews');
const DEFAULT_BODY_BACKGROUND_IMAGE = "url('https://www.sensecore.cn/upload/20230330/crjfafitbja7qufwrt.jpg')";
const fontSizeSlider = document.getElementById('fontSizeSlider');
const fontSizeValue = document.getElementById('fontSizeValue');
let conversationHistory = [];
let uploadedFiles = [];
const essentialElements = [chat, chatContainer, sendBtn, promptTextarea, modelSelect, sendIcon, loadingIcon, buttonText, clearChatBtn, settingsBtn, customApiKeyInput, saveApiKeyBtn, setBgBtn, bgFileInput, apiKeyControls, fileUploadBtn, fileInput, filePreviewsContainer, fontSizeSlider, fontSizeValue];
if (essentialElements.some(el => !el)) {
console.error("CRITICAL ERROR: One or more essential HTML elements not found. Missing elements:", essentialElements.map((el,i) => el ? '' : i).filter(String));
alert("Page load error: Essential chat interface elements are missing. Please check HTML or try later.");
return;
}
console.log("All essential elements found.");
const savedApiKey = localStorage.getItem('customGeminiApiKey');
if (savedApiKey) {
customApiKeyInput.value = savedApiKey;
console.log("Loaded custom API key from localStorage.");
}
function applyChatFontSize(size) {
const newSize = parseInt(size, 10);
if (chat) chat.style.fontSize = \`\${newSize}px\`;
if (fontSizeSlider) fontSizeSlider.value = newSize;
if (fontSizeValue) fontSizeValue.textContent = \`\${newSize}px\`;
localStorage.setItem('chatFontSize', newSize);
}
const savedFontSize = localStorage.getItem('chatFontSize') || '16'; // Default 16px
applyChatFontSize(savedFontSize);
fontSizeSlider.addEventListener('input', function() {
applyChatFontSize(this.value);
});
settingsBtn.addEventListener('click', () => {
apiKeyControls.classList.toggle('hidden');
adjustInputBarLayout();
setTimeout(adjustMainContentPadding, 50);
});
saveApiKeyBtn.addEventListener('click', () => {
const apiKey = customApiKeyInput.value.trim();
if (apiKey) {
localStorage.setItem('customGeminiApiKey', apiKey);
alert('API Key saved locally.');
} else {
localStorage.removeItem('customGeminiApiKey');
alert('Custom API Key cleared.');
}
apiKeyControls.classList.add('hidden');
adjustInputBarLayout();
setTimeout(adjustMainContentPadding, 50);
});
setBgBtn.addEventListener('click', () => {
bgFileInput.click();
});
bgFileInput.addEventListener('change', (event) => {
const file = event.target.files[0];
if (file && file.type.startsWith('image/')) {
const reader = new FileReader();
reader.onload = (e) => {
const oldVideo = document.getElementById('video-bg');
if (oldVideo) oldVideo.remove();
document.body.style.backgroundImage = 'url(' + e.target.result + ')';
const bgData = {
type: 'image',
imageData: e.target.result,
expiry: new Date().getTime() + (24 * 60 * 60 * 1000)
};
localStorage.setItem('customBackgroundData', JSON.stringify(bgData));
};
reader.readAsDataURL(file);
} else if (file && file.type.startsWith('video/')) {
const reader = new FileReader();
reader.onload = (e) => {
document.body.style.backgroundImage = 'none';
const oldVideo = document.getElementById('video-bg');
if (oldVideo) oldVideo.remove();
const videoHTML = \`<video autoplay muted loop id="video-bg">
<source src="\` + e.target.result + \`" type="\` + file.type + \`"
</video>
\`;
document.body.insertAdjacentHTML('afterbegin', videoHTML);
const bgData = {
type: 'video',
videoData: e.target.result,
videoDataUrl: e.target.result,
videoMimeType: file.type,
expiry: new Date().getTime() + (24 * 60 * 60 * 1000)
};
localStorage.setItem('customBackgroundData', JSON.stringify(bgData));
};
reader.readAsDataURL(file);
} else if (file) {
alert('Please select a valid image file.');
}
bgFileInput.value = '';
});
clearChatBtn.addEventListener('click', () => {
chat.innerHTML = '';
conversationHistory = [];
uploadedFiles = [];
filePreviewsContainer.innerHTML = '';
resetToDefaultBackground();
addMessage("你好!请选择一个模型并输入任意问题😀<br>Hi! Get started by selecting any models and input whatever you want!", 'ai', false, 'initial-greeting');
scrollToBottom();
});
fileUploadBtn.addEventListener('click', () => {
fileInput.click();
});
function processAndAddFiles(filesToProcess) {
var alertShownForLimitThisBatch = false;
// filesToProcess can be a FileList or an Array of File objects
for (var i = 0; i < filesToProcess.length; i++) {
var file = filesToProcess[i];
if (uploadedFiles.length >= 10) {
if (!alertShownForLimitThisBatch) {
alert("Maximum 10 files allowed. Some subsequent files from this batch were not added.");
alertShownForLimitThisBatch = true;
}
break; // Stop processing more files from this batch
}
if (file.size > 100 * 1024 * 1024) { // 100MB limit
alert("File '" + file.name + "' is too large (max 100MB) and will not be uploaded.");
continue; // Skip this file, process next in the loop
}
var reader = new FileReader();
// Use an IIFE to correctly capture the 'file' variable for the async onload callback
(function(fileForReader) {
reader.onload = function(e) {
// Final check before pushing, in case limit was hit by other async file reads
if (uploadedFiles.length < 10) {
var base64Data = e.target.result.split(',')[1];
uploadedFiles.push({
name: fileForReader.name,
mimeType: fileForReader.type,
base64Data: base64Data
});
renderFilePreviews(); // This will call adjustMainContentPadding
} else {
// This case might be hit if many small files are processed rapidly and fill the queue
if (!alertShownForLimitThisBatch) {
alert("最多支持上传10文件!Maximum 10 files allowed. File " + fileForReader.name + " could not be added as limit was reached during processing.");
alertShownForLimitThisBatch = true;
}
}
};
reader.readAsDataURL(fileForReader);
})(file);
}
}
fileInput.addEventListener('change', function(event) {
var files = event.target.files;
if (!files) return;
processAndAddFiles(files);
fileInput.value = ''; // Clear the input to allow re-selecting the same file
});
function renderFilePreviews() {
filePreviewsContainer.innerHTML = '';
var filesToRender = uploadedFiles.slice(0, 10);
filesToRender.forEach(function(file) {
var badge = document.createElement('span');
badge.className = 'file-preview-badge';
badge.textContent = file.name.length > 15 ? file.name.substring(0,12) + '...' : file.name;
var removeBtn = document.createElement('span');
removeBtn.className = 'remove-file';
removeBtn.textContent = 'x';
removeBtn.title = 'Remove ' + file.name;
var fileToRemoveOnClick = file;
removeBtn.onclick = function() {
var originalIndex = -1;
for(var i = 0; i < uploadedFiles.length; i++) {if(uploadedFiles[i] === fileToRemoveOnClick) {originalIndex = i;break;}}
if (originalIndex !== -1) {uploadedFiles.splice(originalIndex, 1);} else {console.warn("Could not find file by reference in uploadedFiles to remove it. This may happen if array/object was unexpectedly altered."); }
renderFilePreviews();
};
badge.appendChild(removeBtn);
filePreviewsContainer.appendChild(badge);
});
adjustMainContentPadding();
}
function adjustInputBarLayout() {
const isApiInputVisible = !apiKeyControls.classList.contains('hidden');
if (isApiInputVisible) {
sendBtn.classList.remove('flex-grow');
sendBtn.style.width = 'auto';
} else {
sendBtn.classList.add('flex-grow');
sendBtn.style.width = '';
}
}
adjustInputBarLayout();
promptTextarea.addEventListener('dragover', function(event) {
event.preventDefault(); // Necessary to allow drop
event.stopPropagation();
promptTextarea.classList.add('dragover-active');
});
promptTextarea.addEventListener('dragleave', function(event) {
event.preventDefault();
event.stopPropagation();
promptTextarea.classList.remove('dragover-active');
});
promptTextarea.addEventListener('drop', function(event) {
event.preventDefault();
event.stopPropagation();
promptTextarea.classList.remove('dragover-active');
var files = event.dataTransfer.files;
if (files && files.length > 0) {
processAndAddFiles(files);
}
});
promptTextarea.addEventListener('paste', function(event) {
var clipboardItems = (event.clipboardData || event.originalEvent.clipboardData).items;
var filesToProcess = [];
if (clipboardItems) {
for (var i = 0; i < clipboardItems.length; i++) {
if (clipboardItems[i].kind === 'file') {
var file = clipboardItems[i].getAsFile();
if (file) { filesToProcess.push(file); }
}
}
}
if (filesToProcess.length > 0) {
event.preventDefault(); // Prevent pasting file path as text or file metadata
processAndAddFiles(filesToProcess);
}
});
function setLoadingState(isLoading) {
if (!sendBtn || !promptTextarea || !buttonText || !sendIcon || !loadingIcon) {
console.error("Error inside setLoadingState: Required elements missing.");
return;
}
try {
sendBtn.disabled = isLoading;
promptTextarea.disabled = isLoading;
fileUploadBtn.disabled = isLoading;
clearChatBtn.disabled = isLoading;
settingsBtn.disabled = isLoading;
buttonText.textContent = isLoading ? "处理中..." : "发送 (Post)";
sendIcon.classList.toggle('hidden', isLoading);
loadingIcon.classList.toggle('hidden', !isLoading);
} catch (e) { console.error("Error executing setLoadingState:", e); }
}
function spawnThinkingIcon() {
let icon = document.querySelector('.thinking-icon');
if (icon) icon.remove();
icon = document.createElement('img');
icon.src = 'https://i.ibb.co/ch21FSqt/cf.png';
icon.className = 'thinking-icon';
document.body.appendChild(icon);
icon.addEventListener('animationend', function() { icon.remove(); });
}
function addMessage(textOrParts, sender = 'ai', isLoading = false, messageId = null) {
if (!chat || !modelSelect) { console.error("Error inside addMessage: Chat or modelSelect element not found."); return null; }
try {
let messageDiv = document.createElement('div');
messageDiv.classList.add(sender === 'user' ? 'user-message' : 'ai-message');
if (messageId) messageDiv.id = messageId;
// Apply rainbow bubble class if rainbow theme is active
if (inputBarContainer && inputBarContainer.classList.contains('rainbow-active')) {
messageDiv.classList.add('rainbow-theme-bubble');
}
const senderStrong = document.createElement('strong');
senderStrong.textContent = sender === 'user' ? '你:' : 'AI:';
messageDiv.appendChild(senderStrong);
const contentSpan = document.createElement('span');
contentSpan.className = 'response-content';
if (isLoading) {
const thinkingSpan = document.createElement('span');
thinkingSpan.className = 'thinking';
thinkingSpan.textContent = '🧠深度思考中(Deep Reasoning)...';
messageDiv.appendChild(thinkingSpan);
messageDiv.appendChild(contentSpan);
spawnThinkingIcon();
} else {
if (sender === 'user') {
if (typeof textOrParts === 'string') {
contentSpan.textContent = textOrParts;
} else if (Array.isArray(textOrParts)) {
textOrParts.forEach(part => {
if (part.text) {
const p = document.createElement('p');
p.textContent = part.text;
contentSpan.appendChild(p);
} else if (part.inline_data && part.inline_data.mime_type.startsWith('image/')) {
const img = document.createElement('img');
img.src = 'data:' + part.inline_data.mime_type + ';base64,' + part.inline_data.data;
img.alt = 'Uploaded image';
img.style.maxWidth = '200px'; img.style.maxHeight = '200px'; img.style.borderRadius = '0.375rem'; img.style.marginTop = '0.5rem';
contentSpan.appendChild(img);
} else if (part.file_data) {
const p = document.createElement('p');
p.textContent = '[File: ' + part.file_data.file_name + ']';
contentSpan.appendChild(p);
}
});
}
const pencilBtn = document.createElement('button');
pencilBtn.innerHTML = '✎';
pencilBtn.className = 'edit-prompt-btn';
pencilBtn.title = 'Edit this prompt';
pencilBtn.onclick = function() {
let promptTextToEdit = '';
if (typeof textOrParts === 'string') {
promptTextToEdit = textOrParts;
} else if (Array.isArray(textOrParts)) {
const textPart = textOrParts.find(p => p.text);
if (textPart) promptTextToEdit = textPart.text;
}
promptTextarea.value = promptTextToEdit;
promptTextarea.focus();
};
messageDiv.appendChild(pencilBtn);
} else { // AI message
if (typeof marked !== 'undefined') {
contentSpan.innerHTML = marked.parse(textOrParts);
} else {
contentSpan.textContent = textOrParts;
}
}
messageDiv.appendChild(contentSpan);
}
chat.appendChild(messageDiv);
scrollToBottom();
chatContainer.scrollTop = chatContainer.scrollHeight;
return messageDiv;
} catch (e) { console.error("Error executing addMessage:", e); return null; }
}
addMessage("你好!请选择一个模型并输入任意问题😀<br><br>Hi! Get started by selecting any models and input whatever you want!", 'ai', false, 'initial-greeting');
function scrollToBottom() {
try {
if (chatContainer) {
// 添加平滑滚动效果
chatContainer.scrollTo({
top: chatContainer.scrollHeight,
behavior: 'smooth'
});
}
} catch (e) { console.error("Error scrolling:", e); }
}
function escapeHTML(str) {
if (typeof str !== 'string') return '';
const p = document.createElement('p');
p.appendChild(document.createTextNode(str));
return p.innerHTML;
}
function autoResizeTextarea() {
try {
if (promptTextarea) {
promptTextarea.style.height = 'auto';
let newHeight = promptTextarea.scrollHeight;
const maxHeight = 200;
if (newHeight > maxHeight) {
newHeight = maxHeight;
promptTextarea.style.overflowY = 'auto';
} else {
promptTextarea.style.overflowY = 'hidden';
}
promptTextarea.style.height = newHeight + 'px';
} else { console.error("Error resizing textarea: promptTextarea not found.");}
} catch (e) { console.error("Error executing autoResizeTextarea:", e); }
}
async function handleSend() {
let aiMessageDiv = null;
let responseContentSpan = null;
try {
const promptText = promptTextarea.value.trim();
const model = modelSelect.value;
if (!promptText && uploadedFiles.length === 0) {
alert("请输入你的内容、描述或上传文件!");
promptTextarea.focus(); return;
}
setLoadingState(true);
const userMessageParts = [];
if (promptText) {
userMessageParts.push({ text: promptText });
}
uploadedFiles.forEach(file => {
userMessageParts.push({ inline_data: { mime_type: file.mimeType, data: file.base64Data }, file_data: { file_name: file.name } });
});
addMessage(userMessageParts.length > 0 ? userMessageParts : promptText, 'user');
const currentTurnUserParts = [];
if (promptText) {
currentTurnUserParts.push({ text: promptText });
}
uploadedFiles.forEach(file => {
currentTurnUserParts.push({ inline_data: { mime_type: file.mimeType, data: file.base64Data } });
});
conversationHistory.push({ role: "user", parts: currentTurnUserParts });
promptTextarea.value = '';
uploadedFiles = [];
renderFilePreviews();
autoResizeTextarea();
aiMessageDiv = addMessage('', 'ai', true);
if (!aiMessageDiv) { throw new Error("Failed to create AI placeholder message element."); }
responseContentSpan = aiMessageDiv.querySelector('.response-content');
const thinkingSpan = aiMessageDiv.querySelector('.thinking');
if (!responseContentSpan) { throw new Error("Failed to find response content span in AI placeholder."); }
const requestPayload = {
prompt: promptText,
model: model,
history: conversationHistory.slice(0, -1),
currentTurnParts: currentTurnUserParts
};
const customKey = localStorage.getItem('customGeminiApiKey');
if (customKey) {
requestPayload.customApiKey = customKey;
}
const res = await fetch(location.href, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(requestPayload)
});
if (thinkingSpan) thinkingSpan.remove();
let thinkingIcon = document.querySelector('.thinking-icon');
if (thinkingIcon) thinkingIcon.remove();
if (!res.ok) {
const errorText = await res.text();
console.error("Worker/API Error Response (Status " + res.status + "):", errorText);
if (responseContentSpan && aiMessageDiv) {
responseContentSpan.textContent = "请求出错 (" + res.status + "): " + escapeHTML(errorText.substring(0, 500)) + (errorText.length > 500 ? '...' : '');
aiMessageDiv.classList.add('error-message');
conversationHistory.pop();
scrollToBottom();
} else { console.error("Cannot display fetch error in chat: message elements not found."); }
throw new Error("Server responded with status " + res.status);
}
console.log("Processing Gemini SSE stream...");
const reader = res.body.getReader();
const decoder = new TextDecoder();
let buffer = '';
let currentText = '';
// eslint-disable-next-line no-constant-condition
while (true) {
const { done, value } = await reader.read();
if (done) { console.log("SSE stream finished."); break; }
buffer += decoder.decode(value, { stream: true });
const lines = buffer.split('\\n');
buffer = lines.pop();
for (const line of lines) {
if (line.startsWith('data: ')) {
const jsonStr = line.substring(6).trim();
if (jsonStr === '[DONE]' || !jsonStr) continue;
try {
const chunk = JSON.parse(jsonStr);
const textPart = chunk.candidates?.[0]?.content?.parts?.[0]?.text;
if (textPart) {
currentText += textPart;
if (typeof marked !== 'undefined') {
responseContentSpan.innerHTML = marked.parse(currentText);
} else {
responseContentSpan.textContent = currentText;
}
scrollToBottom();
} else if (chunk.promptFeedback?.blockReason) {
const blockMessage = "\\n[内容被阻止: " + chunk.promptFeedback.blockReason + "]";
currentText += blockMessage;
if (typeof marked !== 'undefined') {
responseContentSpan.innerHTML = marked.parse(currentText);
} else {
responseContentSpan.textContent = currentText;
}
aiMessageDiv.classList.add('error-message');
scrollToBottom();
}
} catch (e) {
console.error("Error parsing streaming JSON chunk:", e, "Chunk:", jsonStr);
const parseErrorMessage = '\\n[解析数据块时出错]';
currentText += parseErrorMessage;
if (typeof marked !== 'undefined') {
responseContentSpan.innerHTML = marked.parse(currentText);
} else {
responseContentSpan.textContent = currentText;
}
scrollToBottom();
}
} else if (line.trim()) { console.log("Received non-data SSE line:", line); }
}
}
if (buffer.trim() && buffer.startsWith('data: ')) {
const jsonStr = buffer.substring(6).trim();
try {
const chunk = JSON.parse(jsonStr);
const textPart = chunk.candidates?.[0]?.content?.parts?.[0]?.text;
if (textPart) {
currentText += textPart;
if (typeof marked !== 'undefined') { responseContentSpan.innerHTML = marked.parse(currentText); }
else { responseContentSpan.textContent = currentText; }
scrollToBottom();
}
} catch (e) {
console.error("Error parsing final buffer:", e);
currentText += '\\n[处理流末尾数据时出错]';
if (typeof marked !== 'undefined') { responseContentSpan.innerHTML = marked.parse(currentText); }
else { responseContentSpan.textContent = currentText; }
scrollToBottom();
}
}
if (currentText) {
conversationHistory.push({ role: "model", parts: [{ text: currentText }] });
} else if (aiMessageDiv.classList.contains('error-message')) {
} else {
responseContentSpan.textContent = "[AI did not provide a text response]";
conversationHistory.push({ role: "model", parts: [{ text: "" }] });
}
console.log("handleSend processing completed successfully.");
} catch (error) {
console.error("CLIENT-SIDE CATCH BLOCK ERROR in handleSend:", error);
if (responseContentSpan) {
if (!responseContentSpan.textContent.includes("出错")) {
responseContentSpan.textContent = '客户端错误: ' + error.message;
}
if (aiMessageDiv && !aiMessageDiv.classList.contains('error-message')) {
aiMessageDiv.classList.add('error-message');
}
scrollToBottom();
} else { console.error("Cannot display error in chat bubble: responseContentSpan not found."); }
} finally {
console.log("CLIENT-SIDE FINALLY BLOCK in handleSend");
setLoadingState(false);
promptTextarea.focus();
let thinkingIcon = document.querySelector('.thinking-icon');
if (thinkingIcon) thinkingIcon.remove();
console.log("UI re-enabled.");
}
}
function resetToDefaultBackground() {
document.body.style.backgroundImage = DEFAULT_BODY_BACKGROUND_IMAGE;
const oldVideo = document.getElementById('video-bg');
if (oldVideo) oldVideo.remove();
localStorage.removeItem('customBackgroundData');
}
const savedBgDataString = localStorage.getItem('customBackgroundData');
if (savedBgDataString) {
try {
const savedBgData = JSON.parse(savedBgDataString);
if (savedBgData && savedBgData.expiry && new Date().getTime() < savedBgData.expiry) {
if (savedBgData.type === 'video' && savedBgData.videoDataUrl && savedBgData.videoMimeType) {
document.body.style.backgroundImage = 'none';
const oldVideo = document.getElementById('video-bg');
if (oldVideo) oldVideo.remove();
const videoHTML = \`<video autoplay muted loop id="video-bg">
<source src="\` + savedBgData.videoDataUrl + \`" type="\` + savedBgData.videoMimeType + \`">
</video>
\`;
document.body.insertAdjacentHTML('afterbegin', videoHTML);
} else if (savedBgData.type === 'image' && savedBgData.imageData) {
const oldVideo = document.getElementById('video-bg');
if (oldVideo) oldVideo.remove();
document.body.style.backgroundImage = 'url(' + savedBgData.imageData + ')';
} else {
resetToDefaultBackground();
}
} else {
resetToDefaultBackground();
}
} catch (e) {
console.error("Error parsing custom background data:", e);
resetToDefaultBackground();
}
}
sendBtn.addEventListener('click', handleSend);
promptTextarea.addEventListener('keypress', (e) => { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); handleSend(); } });
promptTextarea.addEventListener('input', autoResizeTextarea);
autoResizeTextarea();
window.addEventListener('resize', adjustMainContentPadding);
console.log("Event listeners attached and initial setup done.");
});
</script>
`;
// Main HTML structure
export function renderHTML(isMobile) {
const styles = getStyles();
const clientScript = getClientScript();
const viewportMeta = isMobile
? '<meta name="viewport" content="width=1024"> <!-- Forcing desktop-like viewport for mobile -->'
: '<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">';
return `<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">${viewportMeta}
<title>輕音Joy-AI公益站</title>
<link rel="icon" href="https://www.cloudflare.com/favicon.ico" type="image/x-icon">
<script src="https://cdn.tailwindcss.com"></script>
<script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
` + styles + `
</head>
<style>
a {color: rgba(var(--link-text-rgb), 0.9)!important;text-shadow: 0 2px 4px rgba(var(--link-text-rgb), 0.3);}
a:hover {color: rgba(var(--link-text-rgb), 1)!important;text-decoration: underline;}
.hidden { display: none !important; }
</style>
<body class="bg-gray-900 text-gray-100 font-sans">
<div class="main-content-area">
<div class="p-0 text-center mb-1">
<h1 class="text-3xl font-bold my-1">Ultra AI ☁ Cloudflare 輕音Joy-AI公益站</h1>
<a href="https://www.qyjoy.vip" target="_blank" class="block font-bold cursor-pointer mb-1 animate-breathe" style="text-shadow:0 0 3px rgba(150, 255, 3, 0.97);">Serverless Powered By ⚡ 抖音|Bilibili|Youtube|网易云|公众号:輕音Joy</a>
</div>
<div class="px-4 sm:px-6 pb-0">
<div class="flex flex-col sm:flex-row gap-3 my-1">
<div class="w-full sm:w-1/2">
<label for="model" class="block mb-1 text-sm font-medium text-gray-300">👆选择模型 Choose A Model:</label>
<select id="model" class="w-full p-2.5 rounded border text-white focus:ring-blue-500 focus:border-blue-500">
<option value="gemini-2.0-flash" selected>Gemini 2.0 Flash ⚡ (Popular)</option>
<option value="gemini-2.5-flash-preview-05-20">Gemini 2.5 Preview 🔥 (Hot)</option>
<option value="gemini-2.5-pro-preview-06-05">Gemini 2.5 Pro Preview ⚙ (请在设置中填入自己的API)</option>
<option value="gemini-2.0-flash-preview-image-generation">Gemini Image Gen 图片生成 🛠️ (需在设置中填入自己的API)</option>
<option value="veo-2.0-generate-001">Gemini Veo2 视频生成 🎬 (需在设置中填入自己的API)</option>
<option value="" disabled>ChatGPT 4.5 🧪 (研发中-敬请期待)</option>
<option value="" disabled>Claude 3.7 🔬 (研发中-敬请期待)</option>
<option value="" disabled>Cursor 💡 (研发中-敬请期待)</option>
</select>
</div>
<div class="w-full sm:w-1/2">
<label for="theme" class="block mb-1 text-sm font-medium text-gray-300">🎨主题颜色 Theme color:</label>
<select id="theme" class="w-full p-2.5 rounded border text-white">
<option value="rainbow" selected>🌈彩虹呼吸 Rainbow Breathing</option>
<option value="cyberpunk">💿赛博霓虹 Cyberpunk Neon</option>
<option value="prism">💠幻彩棱镜 Iridescent Prism</option>
<option value="blue">🔵科技蓝 Tech Blue</option>
<option value="purple">🟣梦幻紫 Dreamy Purple</option>
<option value="green">🟢自然绿 Natural Green</option>
<option value="pink">💖少女粉 Soft Pink</option>
<option value="gradient">🟠渐变紫橙 Gradient Purple-Orange</option>
<option value="red">🔴热情红 Passionate Red</option>
<option value="yellow">🟡活力黄 Vibrant Yellow</option>
</select>
</div>
</div>
</div>
<div id="chat-container" class="flex-grow px-2 pb-1">
<div id="chat" class="flex flex-col space-y-2 p-1">
</div>
</div>
</div>
<div class="input-bar-container bg-transparent">
<div id="filePreviews" class="fixed bottom-[60px] left-4 right-4 max-h-[30vh] overflow-y-auto rounded-lg shadow-lg z-10"></div>
<div class="flex items-end gap-2 relative">
<button id="fileUploadBtn" title="Upload Files" class="p-2.5 rounded text-white hover:bg-gray-700 transition-colors">
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="12" y1="5" x2="12" y2="19"></line><line x1="5" y1="12" x2="19" y2="12"></line></svg>
</button>
<input type="file" id="fileUpload" multiple accept=".ini,.txt,.doc,.docx,.pdf,text/*,image/*,application/pdf,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document" class="hidden">
<textarea id="prompt" rows="1" class="flex-grow p-2.5 rounded border text-white focus:ring-blue-500 focus:border-blue-500" placeholder="输入你的任意问题... (Input whatever you want here...)"></textarea>
<button id="sendBtn" class="flex-grow sm:flex-grow-0 flex items-center justify-center gap-2 p-2.5 rounded font-semibold text-white/90 transition duration-150 ease-in-out disabled:opacity-50 disabled:cursor-not-allowed" style="min-width: 120px; border:1px solid rgba(255,255,255,0.8)!important;box-shadow:0 2px 8px rgba(0,0,0,0.1)">
<img src="https://www.cloudflare.com/favicon.ico" alt="Cloudflare" class="w-4 h-4">
<span class="button-text">发送 Post</span><span id="sendIcon">➤</span><span id="loadingIcon" class="loader hidden"></span>
</button>
<button id="clearChatBtn" title="Clear Chat & Memory" class="p-2.5 rounded text-white hover:bg-gray-700 transition-colors">
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="3 6 5 6 21 6"></polyline><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"></path><line x1="10" y1="11" x2="10" y2="17"></line><line x1="14" y1="11" x2="14" y2="17"></line></svg>
</button>
<button id="settingsBtn" title="Settings / Custom API Key" class="p-2.5 rounded text-white hover:bg-gray-700 transition-colors">
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="3"></circle><path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1 0 2.83 2 2 0 0 1-2.83 0l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-2 2 2 2 0 0 1-2-2v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83 0 2 2 0 0 1 0-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1-2-2 2 2 0 0 1 2-2h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 0-2.83 2 2 0 0 1 2.83 0l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 2-2 2 2 0 0 1 2 2v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 0 2 2 0 0 1 0 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 2 2 2 2 0 0 1-2 2h-.09a1.65 1.65 0 0 0-1.51 1z"></path></svg>
</button>
</div>
<div id="apiKeyControls" class="hidden mt-2 flex items-center gap-2">
<input type="password" id="customApiKey" placeholder="输入自定义API (Enter Your Own API Key if needed)" class="flex-grow p-2 rounded border text-white" style="min-width: 180px;">
<button id="saveApiKeyBtn" class="p-2 rounded bg-blue-600 hover:bg-blue-700 text-white font-semibold">保存API(Save)</button>
<div id="fontSizeControlContainer" class="flex items-center gap-2 flex-grow" style="min-width: 200px; max-width:300px;">
<label for="fontSizeSlider" class="text-sm text-gray-300 whitespace-nowrap">字号(FontSize):</label>
<input type="range" id="fontSizeSlider" m
gitextract_dmkitj7p/ ├── .github/ │ └── ISSUE_TEMPLATE/ │ ├── cn.yaml │ ├── config.yml │ ├── en.yaml │ └── ru.yaml ├── All in one Portable(outdated)/ │ └── AI-WorkerOldRelease.js ├── LICENSE ├── README.md ├── V3(stable)/ │ ├── api-handler.js │ ├── html-rendererv3.js │ ├── request-handler.js │ ├── utils.js │ └── worker.js ├── V4 EX(For mobile support Expand)/ │ ├── api-handler.js │ ├── html-renderer.js │ ├── request-handler.js │ ├── utils.js │ └── worker.js ├── V4(latest)/ │ ├── api-handler.js │ ├── html-renderer.js │ ├── request-handler.js │ ├── utils.js │ └── worker.js └── autoRenice.sh
SYMBOL INDEX (18 symbols across 16 files)
FILE: All in one Portable(outdated)/AI-WorkerOldRelease.js
function corsHeaders (line 2) | function corsHeaders()
function renderHTML (line 9) | function renderHTML() {
method fetch (line 494) | async fetch(request, env, ctx) {
FILE: V3(stable)/api-handler.js
function handleApiCall (line 6) | async function handleApiCall(request, env, logPrefix) {
FILE: V3(stable)/html-rendererv3.js
function renderHTML (line 578) | function renderHTML() {
FILE: V3(stable)/request-handler.js
function handleRequest (line 7) | async function handleRequest(request, env, ctx, logPrefix) {
FILE: V3(stable)/utils.js
function corsHeaders (line 4) | function corsHeaders() {
FILE: V3(stable)/worker.js
method fetch (line 7) | async fetch(request, env, ctx) {
FILE: V4 EX(For mobile support Expand)/api-handler.js
function handleApiCall (line 2) | async function handleApiCall(request, env, logPrefix) {
FILE: V4 EX(For mobile support Expand)/html-renderer.js
function renderHTML (line 1103) | function renderHTML(isMobile) {
FILE: V4 EX(For mobile support Expand)/request-handler.js
function handleRequest (line 7) | async function handleRequest(request, env, ctx, logPrefix, isMobile) {
FILE: V4 EX(For mobile support Expand)/utils.js
function corsHeaders (line 4) | function corsHeaders() {
FILE: V4 EX(For mobile support Expand)/worker.js
method fetch (line 7) | async fetch(request, env, ctx) {
FILE: V4(latest)/api-handler.js
function handleApiCall (line 6) | async function handleApiCall(request, env, logPrefix) {
FILE: V4(latest)/html-renderer.js
function renderHTML (line 761) | function renderHTML() {
FILE: V4(latest)/request-handler.js
function handleRequest (line 7) | async function handleRequest(request, env, ctx, logPrefix) {
FILE: V4(latest)/utils.js
function corsHeaders (line 4) | function corsHeaders() {
FILE: V4(latest)/worker.js
method fetch (line 7) | async fetch(request, env, ctx) {
Condensed preview — 23 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (281K chars).
[
{
"path": ".github/ISSUE_TEMPLATE/cn.yaml",
"chars": 1621,
"preview": "name: ⚠功能性問題回報\ndescription: 回報一個明確的功能性錯誤,例如按鈕無效或邏輯錯誤\ntitle: \"標題:請簡要描述問題\"\nlabels: [enhancement, question, documentation, "
},
{
"path": ".github/ISSUE_TEMPLATE/config.yml",
"chars": 600,
"preview": "blank_issues_enabled: false\n\ncontact_links:\n - name: ⛔ [RU]Пожалуйста, не отправляйте нефункциональные проблемы здесь\n "
},
{
"path": ".github/ISSUE_TEMPLATE/en.yaml",
"chars": 2436,
"preview": "name: ⚠Functional Issue Report\ndescription: Report a clear functional error, such as a button not working or a logic bug"
},
{
"path": ".github/ISSUE_TEMPLATE/ru.yaml",
"chars": 1977,
"preview": "name: ⚠Сообщение о функциональной проблеме\ndescription: Сообщите о чёткой функциональной ошибке, например, неработающей "
},
{
"path": "All in one Portable(outdated)/AI-WorkerOldRelease.js",
"chars": 36606,
"preview": "// Helper Function for CORS Headers\nfunction corsHeaders() \n {return {\n \"Access-Control-Allow-Origin\": \"*\", // W"
},
{
"path": "LICENSE",
"chars": 35821,
"preview": " GNU GENERAL PUBLIC LICENSE\r\n Version 3, 29 June 2007\r\n\r\n Copyright (C) 2007 Fr"
},
{
"path": "README.md",
"chars": 13799,
"preview": "<p align=\"center\">\n <a href=\"https://www.cloudflare.com/\"><img src=\"https://cf-assets.www.cloudflare.com/zkvhlag99gkb/m"
},
{
"path": "V3(stable)/api-handler.js",
"chars": 7559,
"preview": "// api-handler.js\n// Handles communication with the Google Generative AI API.\n\nimport { corsHeaders } from './utils.js';"
},
{
"path": "V3(stable)/html-rendererv3.js",
"chars": 31214,
"preview": "// html-renderer.js// Generates the complete HTML page, including CSS and client-side JavaScript.// CSS styles for the p"
},
{
"path": "V3(stable)/request-handler.js",
"chars": 1753,
"preview": "// request-handler.js\n// Handles incoming requests, routing, and basic validation.\nimport { renderHTML } from './html-re"
},
{
"path": "V3(stable)/utils.js",
"chars": 403,
"preview": "// utils.js\n// Utility functions for the worker.\n\nexport function corsHeaders() {\n return {\n \"Access-Control-All"
},
{
"path": "V3(stable)/worker.js",
"chars": 525,
"preview": "// worker.js\n// Main entry point for the Cloudflare Worker.\n\nimport { handleRequest } from './request-handler.js';\n\nexpo"
},
{
"path": "V4 EX(For mobile support Expand)/api-handler.js",
"chars": 5496,
"preview": "import { corsHeaders } from './utils.js';\r\nexport async function handleApiCall(request, env, logPrefix) {\r\n console.log"
},
{
"path": "V4 EX(For mobile support Expand)/html-renderer.js",
"chars": 58815,
"preview": "const getStyles = () => `\r\n<style>\r\n#video-bg {position: fixed;right: 0;bottom: 0;min-width: 100%;min-height: 100%;z-ind"
},
{
"path": "V4 EX(For mobile support Expand)/request-handler.js",
"chars": 2092,
"preview": "// request-handler.js\r\n// Handles incoming requests, routing, and basic validation.\r\nimport { renderHTML } from './html-"
},
{
"path": "V4 EX(For mobile support Expand)/utils.js",
"chars": 275,
"preview": "// utils.js\r\n// Utility functions for the worker.\r\n\r\nexport function corsHeaders() {\r\n return {\r\n \"Access-Control-Al"
},
{
"path": "V4 EX(For mobile support Expand)/worker.js",
"chars": 768,
"preview": "// worker.js\r\n// Main entry point for the Cloudflare Worker.\r\n\r\nimport { handleRequest } from './request-handler.js';\r\n\r"
},
{
"path": "V4(latest)/api-handler.js",
"chars": 5202,
"preview": "// api-handler.js\n// Handles communication with the Google Generative AI API.\n\nimport { corsHeaders } from './utils.js';"
},
{
"path": "V4(latest)/html-renderer.js",
"chars": 42405,
"preview": "// html-renderer.js\n// Generates the complete HTML page, including CSS and client-side JavaScript.\n\n// CSS styles for th"
},
{
"path": "V4(latest)/request-handler.js",
"chars": 2026,
"preview": "// request-handler.js\n// Handles incoming requests, routing, and basic validation.\nimport { renderHTML } from './html-re"
},
{
"path": "V4(latest)/utils.js",
"chars": 266,
"preview": "// utils.js\n// Utility functions for the worker.\n\nexport function corsHeaders() {\n return {\n \"Access-Control-Allow-O"
},
{
"path": "V4(latest)/worker.js",
"chars": 449,
"preview": "// worker.js\n// Main entry point for the Cloudflare Worker.\n\nimport { handleRequest } from './request-handler.js';\n\nexpo"
},
{
"path": "autoRenice.sh",
"chars": 10019,
"preview": "#!/bin/bash\nset -e\nset -o pipefail\n\nPATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin\nexport PATH\n"
}
]
About this extraction
This page contains the full source code of the qyjoy/AI-worker GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 23 files (256.0 KB), approximately 68.8k tokens, and a symbol index with 18 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.