Team Ai
Apppublic

devin15/cursor2api-rust

sourceHugging Faceupdated 2y agoView on Hugging Face
0likes
shared.js241 linesDownload Raw Back to static
1// Token 管理功能2function saveAuthToken(token) {3  const expiryTime = new Date().getTime() + (24 * 60 * 60 * 1000); // 24小时后过期4  localStorage.setItem('authToken', token);5  localStorage.setItem('authTokenExpiry', expiryTime);6}7 8function getAuthToken() {9  const token = localStorage.getItem('authToken');10  const expiry = localStorage.getItem('authTokenExpiry');11 12  if (!token || !expiry) {13    return null;14  }15 16  if (new Date().getTime() > parseInt(expiry)) {17    localStorage.removeItem('authToken');18    localStorage.removeItem('authTokenExpiry');19    return null;20  }21 22  return token;23}24 25// 消息显示功能26function showMessage(elementId, text, isError = false) {27  const msg = document.getElementById(elementId);28  msg.className = `message ${isError ? 'error' : 'success'}`;29  msg.textContent = text;30}31 32function showGlobalMessage(text, isError = false) {33  showMessage('message', text, isError);34  // 3秒后自动清除消息35  setTimeout(() => {36    const msg = document.getElementById('message');37    msg.textContent = '';38    msg.className = 'message';39  }, 3000);40}41 42// Token 输入框自动填充和事件绑定43function initializeTokenHandling(inputId) {44  document.addEventListener('DOMContentLoaded', () => {45    const authToken = getAuthToken();46    if (authToken) {47      document.getElementById(inputId).value = authToken;48    }49  });50 51  document.getElementById(inputId).addEventListener('change', (e) => {52    if (e.target.value) {53      saveAuthToken(e.target.value);54    } else {55      localStorage.removeItem('authToken');56      localStorage.removeItem('authTokenExpiry');57    }58  });59}60 61// API 请求通用处理62async function makeAuthenticatedRequest(url, options = {}) {63  const tokenId = options.tokenId || 'authToken';64  const token = document.getElementById(tokenId).value;65 66  if (!token) {67    showGlobalMessage('请输入 AUTH_TOKEN', true);68    return null;69  }70 71  const defaultOptions = {72    method: 'POST',73    headers: {74      'Authorization': `Bearer ${token}`,75      'Content-Type': 'application/json'76    }77  };78 79  try {80    const response = await fetch(url, { ...defaultOptions, ...options });81 82    if (!response.ok) {83      throw new Error(`HTTP error! status: ${response.status}`);84    }85 86    return await response.json();87  } catch (error) {88    showGlobalMessage(`请求失败: ${error.message}`, true);89    return null;90  }91}92 93/**94 * 从字符串解析布尔值95 * @param {string} str - 要解析的字符串96 * @param {boolean|null} defaultValue - 解析失败时的默认值97 * @returns {boolean|null} 解析结果,如果无法解析则返回默认值98 */99function parseBooleanFromString(str, defaultValue = null) {100  if (typeof str !== 'string') {101    return defaultValue;102  }103 104  const lowercaseStr = str.toLowerCase().trim();105 106  if (lowercaseStr === 'true' || lowercaseStr === '1') {107    return true;108  } else if (lowercaseStr === 'false' || lowercaseStr === '0') {109    return false;110  } else {111    return defaultValue;112  }113}114 115/**116 * 将布尔值转换为字符串117 * @param {boolean|undefined|null} value - 要转换的布尔值118 * @param {string} defaultValue - 转换失败时的默认值119 * @returns {string} 转换结果,如果输入无效则返回默认值120 */121function parseStringFromBoolean(value, defaultValue = null) {122  if (typeof value !== 'boolean') {123    return defaultValue;124  }125 126  return value ? 'true' : 'false';127}128 129/**130 * 解析对话内容131 * @param {string} promptStr - 原始prompt字符串132 * @returns {Array<{role: string, content: string}>} 解析后的对话数组133 */134function parsePrompt(promptStr) {135  if (!promptStr) return [];136 137  const messages = [];138  const lines = promptStr.split('\n');139  let currentRole = '';140  let currentContent = '';141 142  const roleMap = {143    'BEGIN_SYSTEM': 'system',144    'BEGIN_USER': 'user',145    'BEGIN_ASSISTANT': 'assistant'146  };147 148  for (let i = 0; i < lines.length; i++) {149    const line = lines[i];150 151    // 检查是否是角色标记行152    let foundRole = false;153    for (const [marker, role] of Object.entries(roleMap)) {154      if (line.includes(marker)) {155        // 保存之前的消息(如果有)156        if (currentRole && currentContent.trim()) {157          messages.push({158            role: currentRole,159            content: currentContent.trim()160          });161        }162        // 设置新角色163        currentRole = role;164        currentContent = '';165        foundRole = true;166        break;167      }168    }169 170    // 如果不是角色标记行且不是END标记行,则添加到当前内容171    if (!foundRole && !line.includes('END_')) {172      currentContent += line + '\n';173    }174  }175 176  // 添加最后一条消息177  if (currentRole && currentContent.trim()) {178    messages.push({179      role: currentRole,180      content: currentContent.trim()181    });182  }183 184  return messages;185}186 187/**188 * 格式化对话内容为HTML表格189 * @param {Array<{role: string, content: string}>} messages - 对话消息数组190 * @returns {string} HTML表格字符串191 */192function formatPromptToTable(messages) {193  if (!messages || messages.length === 0) {194    return '<p>无对话内容</p>';195  }196 197  const roleLabels = {198    'system': '系统',199    'user': '用户',200    'assistant': '助手'201  };202 203  function escapeHtml(content) {204    // 先转义HTML特殊字符205    const escaped = content206      .replace(/&/g, '&amp;')207      .replace(/</g, '&lt;')208      .replace(/>/g, '&gt;')209      .replace(/"/g, '&quot;')210      .replace(/'/g, '&#039;');211 212    // 将HTML标签文本用引号包裹,使其更易读213    // return escaped.replace(/&lt;(\/?[^>]+)&gt;/g, '"<$1>"');214    return escaped;215  }216 217  return `<table class="message-table"><thead><tr><th>角色</th><th>内容</th></tr></thead><tbody>${messages.map(msg => `<tr><td>${roleLabels[msg.role] || msg.role}</td><td>${escapeHtml(msg.content).replace(/\n/g, '<br>')}</td></tr>`).join('')}</tbody></table>`;218}219 220/**221 * 安全地显示prompt对话框222 * @param {string} promptStr - 原始prompt字符串223 */224function showPromptModal(promptStr) {225  try {226    const modal = document.getElementById('promptModal');227    const content = document.getElementById('promptContent');228 229    if (!modal || !content) {230      console.error('Modal elements not found');231      return;232    }233 234    const messages = parsePrompt(promptStr);235    content.innerHTML = formatPromptToTable(messages);236    modal.style.display = 'block';237  } catch (e) {238    console.error('显示prompt对话框失败:', e);239    console.error('原始prompt:', promptStr);240  }241}