commit 6dca025e967f1e100ffd76473b121a5abe0d780e Author: 1e0n Date: Mon Oct 6 02:12:01 2025 +0800 Initial commit: OpenAI compatible API proxy with auto token refresh - Implemented OpenAI compatible API proxy server - Support for Anthropic and custom OpenAI format conversion - Automatic API key refresh with WorkOS OAuth - SSE streaming response transformation - Smart header management for Factory endpoints - Chinese documentation diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..8a433ab --- /dev/null +++ b/.gitignore @@ -0,0 +1,4 @@ +node_modules/ +*.log +.env +.DS_Store diff --git a/README.md b/README.md new file mode 100644 index 0000000..e5a60ef --- /dev/null +++ b/README.md @@ -0,0 +1,293 @@ +# droid2api + +OpenAI 兼容 API 代理服务器,用于在不同 LLM API 格式之间进行转换。 + +## 功能特性 + +- **标准 OpenAI API 接口**:提供完全兼容 OpenAI 的 API 端点 +- **多格式支持**:支持 Anthropic 和自定义 OpenAI 格式之间的自动转换 +- **流式响应**:自动转换 SSE (Server-Sent Events) 流式响应为标准 OpenAI 格式 +- **自动刷新 API Key**:集成 WorkOS 认证,自动管理和刷新访问令牌(8小时有效期,每6小时自动刷新) +- **智能 Header 管理**:自动添加和管理所有必需的 Factory 特定 headers +- **配置化路由**:通过 config.json 灵活配置模型和端点映射 +- **开发模式**:详细的日志输出,便于调试 + +## 安装 + +```bash +npm install +``` + +## 配置 + +### 1. 配置端点和模型 + +编辑 `config.json` 文件: + +```json +{ + "port": 3000, + "endpoint": [ + { + "name": "openai", + "base_url": "https://app.factory.ai/api/llm/o/v1/responses" + }, + { + "name": "anthropic", + "base_url": "https://app.factory.ai/api/llm/a/v1/messages" + } + ], + "models": [ + { + "name": "Claude Opus 4", + "id": "claude-opus-4-1-20250805", + "type": "anthropic" + }, + { + "name": "GPT-5 Codex", + "id": "gpt-5-codex", + "type": "openai" + } + ], + "dev_mode": false +} +``` + +### 2. 配置认证(二选一) + +#### 方式一:使用环境变量(推荐用于开发/测试) + +```bash +export DROID_REFRESH_KEY="your_refresh_token_here" +``` + +刷新后的 API key 会保存到工作目录的 `auth.json` 文件。 + +#### 方式二:使用配置文件(推荐用于生产环境) + +确保 `~/.factory/auth.json` 文件存在并包含有效的 tokens: + +```json +{ + "access_token": "your_access_token_here", + "refresh_token": "your_refresh_token_here" +} +``` + +刷新后的 tokens 会自动更新到原文件。 + +## 使用方法 + +### 启动服务器 + +```bash +npm start +``` + +或使用快捷脚本: + +```bash +./start.sh +``` + +服务器默认运行在 `http://localhost:3000`。 + +### API 端点 + +#### 1. 获取可用模型列表 + +```bash +GET /v1/models +``` + +**示例:** +```bash +curl http://localhost:3000/v1/models +``` + +**响应:** +```json +{ + "object": "list", + "data": [ + { + "id": "claude-opus-4-1-20250805", + "object": "model", + "created": 1704067200000, + "owned_by": "factory" + } + ] +} +``` + +#### 2. 对话补全(兼容 OpenAI) + +```bash +POST /v1/chat/completions +``` + +**请求参数:** +- `model` (必需): 模型 ID +- `messages` (必需): 对话消息数组 +- `stream` (可选): 是否使用流式响应,默认 true +- `max_tokens` (可选): 最大输出 tokens 数 +- `temperature` (可选): 温度参数 0-1 +- `top_p` (可选): Top-p 采样参数 + +**示例(流式响应):** +```bash +curl http://localhost:3000/v1/chat/completions \ + -H "Content-Type: application/json" \ + -d '{ + "model": "claude-opus-4-1-20250805", + "messages": [ + {"role": "user", "content": "你好,请介绍一下你自己"} + ], + "stream": true, + "max_tokens": 2000 + }' +``` + +**示例(非流式响应):** +```bash +curl http://localhost:3000/v1/chat/completions \ + -H "Content-Type: application/json" \ + -d '{ + "model": "gpt-5-codex", + "messages": [ + {"role": "user", "content": "写一个 Python 快速排序"} + ], + "stream": false + }' +``` + +## API Key 自动刷新机制 + +代理服务器会自动管理 API key 的刷新: + +1. **启动时刷新**:服务器启动时自动获取新的 access token +2. **定期刷新**:每次 API 请求前检查,如果距离上次刷新超过 6 小时则自动刷新 +3. **令牌有效期**:access token 有效期为 8 小时 +4. **自动保存**:刷新后的 tokens 自动保存到相应的配置文件 + +**刷新日志示例:** +``` +[INFO] Refreshing API key... +[INFO] Authenticated as: user@example.com (John Doe) +[INFO] User ID: user_01K69S755R2TWYFWKPSP74TRKZ +[INFO] Organization ID: org_01K69S7KKYK6F2WYJ8CB384GW6 +[INFO] API key refreshed successfully +``` + +## 格式转换说明 + +### Anthropic 格式转换 + +**请求转换:** +- `messages` → `messages`(提取 system 消息到顶层) +- `max_tokens` → `max_tokens`(默认 4096) +- 文本内容包装为 `{type: 'text', text: '...'}` +- 工具格式转换 + +**响应转换:** +- 转换 SSE 事件:`message_start`, `content_block_delta`, `message_delta`, `message_stop` +- 转换为标准 OpenAI chunk 格式 +- 映射停止原因:`end_turn` → `stop`, `max_tokens` → `length` + +### OpenAI 格式转换 + +**请求转换:** +- `messages` → `input` +- `max_tokens` → `max_output_tokens` +- 用户消息:`text` → `input_text` +- 助手消息:`text` → `output_text` +- 提取 system 消息为 `instructions` 参数 + +**响应转换:** +- 转换 SSE 事件:`response.created`, `response.in_progress`, `response.done` +- 转换为标准 OpenAI chunk 格式 + +## Header 管理 + +代理服务器会自动添加所有必需的 headers: + +### Anthropic 端点 +- `x-model-provider: anthropic` +- `x-factory-client: cli` +- `user-agent: a$/JS 0.57.0` +- `anthropic-version: 2023-06-01` +- `anthropic-beta: interleaved-thinking-2025-05-14` +- `x-stainless-helper-method: stream`(流式请求) +- 自动生成的 UUID:`x-session-id`, `x-assistant-message-id` + +### OpenAI 端点 +- `x-factory-client: cli` +- `user-agent: cB/JS 5.22.0` +- 自动生成的 UUID:`x-session-id`, `x-assistant-message-id` + +## 开发模式 + +在 `config.json` 中设置 `dev_mode: true` 可以启用详细日志: + +```json +{ + "dev_mode": true +} +``` + +**日志内容包括:** +- 完整的请求和响应 headers +- 请求体和响应体 +- 格式转换过程 +- SSE 事件处理详情 + +## 端口冲突处理 + +如果端口 3000 已被占用,可以: + +1. **修改配置文件**:编辑 `config.json` 中的 `port` 字段 +2. **或者结束占用进程**: + ```bash + lsof -ti:3000 | xargs kill -9 + ``` + +## 故障排查 + +### 启动时报错 "Refresh token not found" + +**原因**:未配置 refresh token + +**解决方案**: +- 设置环境变量 `DROID_REFRESH_KEY` +- 或配置 `~/.factory/auth.json` 文件 + +### 请求返回 401 错误 + +**可能原因**: +1. refresh token 已过期或无效 +2. API key 刷新失败 + +**解决方案**: +- 检查日志中的刷新错误信息 +- 重新获取有效的 refresh token +- 确认 `~/.factory/auth.json` 中的 tokens 正确 + +### 响应格式错误 + +**原因**:模型类型配置错误 + +**解决方案**: +- 检查 `config.json` 中模型的 `type` 字段 +- Anthropic 模型使用 `"type": "anthropic"` +- OpenAI 模型使用 `"type": "openai"` + +## 技术架构 + +- **语言**:Node.js (ES Modules) +- **框架**:Express +- **HTTP 客户端**:node-fetch +- **认证**:WorkOS OAuth 2.0 Refresh Token Flow + +## 许可证 + +MIT diff --git a/auth.js b/auth.js new file mode 100644 index 0000000..d270784 --- /dev/null +++ b/auth.js @@ -0,0 +1,268 @@ +import fs from 'fs'; +import path from 'path'; +import os from 'os'; +import fetch from 'node-fetch'; +import { logDebug, logError, logInfo } from './logger.js'; + +// State management for API key and refresh +let currentApiKey = null; +let currentRefreshToken = null; +let lastRefreshTime = null; +let clientId = null; +let authSource = null; // 'env' or 'file' +let authFilePath = null; + +const REFRESH_URL = 'https://api.workos.com/user_management/authenticate'; +const REFRESH_INTERVAL_HOURS = 6; // Refresh every 6 hours +const TOKEN_VALID_HOURS = 8; // Token valid for 8 hours + +/** + * Generate a ULID (Universally Unique Lexicographically Sortable Identifier) + * Format: 26 characters using Crockford's Base32 + * First 10 chars: timestamp (48 bits) + * Last 16 chars: random (80 bits) + */ +function generateULID() { + // Crockford's Base32 alphabet (no I, L, O, U to avoid confusion) + const ENCODING = '0123456789ABCDEFGHJKMNPQRSTVWXYZ'; + + // Get timestamp in milliseconds + const timestamp = Date.now(); + + // Encode timestamp to 10 characters + let time = ''; + let ts = timestamp; + for (let i = 9; i >= 0; i--) { + const mod = ts % 32; + time = ENCODING[mod] + time; + ts = Math.floor(ts / 32); + } + + // Generate 16 random characters + let randomPart = ''; + for (let i = 0; i < 16; i++) { + const rand = Math.floor(Math.random() * 32); + randomPart += ENCODING[rand]; + } + + return time + randomPart; +} + +/** + * Generate a client ID in format: client_01{ULID} + */ +function generateClientId() { + const ulid = generateULID(); + return `client_01${ulid}`; +} + +/** + * Load initial refresh token from environment or config file + */ +function loadRefreshToken() { + // 1. Check environment variable DROID_REFRESH_KEY + const envRefreshKey = process.env.DROID_REFRESH_KEY; + if (envRefreshKey && envRefreshKey.trim() !== '') { + logInfo('Using refresh token from DROID_REFRESH_KEY environment variable'); + authSource = 'env'; + authFilePath = path.join(process.cwd(), 'auth.json'); + return envRefreshKey.trim(); + } + + // 2. Check ~/.factory/auth.json + const homeDir = os.homedir(); + const factoryAuthPath = path.join(homeDir, '.factory', 'auth.json'); + + try { + if (fs.existsSync(factoryAuthPath)) { + const authContent = fs.readFileSync(factoryAuthPath, 'utf-8'); + const authData = JSON.parse(authContent); + + if (authData.refresh_token && authData.refresh_token.trim() !== '') { + logInfo('Using refresh token from ~/.factory/auth.json'); + authSource = 'file'; + authFilePath = factoryAuthPath; + + // Also load access_token if available + if (authData.access_token) { + currentApiKey = authData.access_token.trim(); + } + + return authData.refresh_token.trim(); + } + } + } catch (error) { + logError('Error reading ~/.factory/auth.json', error); + } + + // 3. No refresh token found - throw error + const errorMessage = ` +╔════════════════════════════════════════════════════════════════╗ +║ Refresh Token Not Found ║ +╚════════════════════════════════════════════════════════════════╝ + +No valid refresh token found. Please use one of the following methods: + +1. Set environment variable: + export DROID_REFRESH_KEY="your_refresh_token_here" + +2. Or ensure ~/.factory/auth.json exists with valid refresh_token: + { + "access_token": "your_access_token", + "refresh_token": "your_refresh_token" + } + +Current status: + - DROID_REFRESH_KEY: ${envRefreshKey ? 'empty or whitespace' : 'not set'} + - ~/.factory/auth.json: ${fs.existsSync(factoryAuthPath) ? 'exists but invalid/empty refresh_token' : 'not found'} +`; + + logError(errorMessage); + throw new Error('Refresh token not found. Please configure DROID_REFRESH_KEY or ~/.factory/auth.json'); +} + +/** + * Refresh API key using refresh token + */ +async function refreshApiKey() { + if (!currentRefreshToken) { + throw new Error('No refresh token available'); + } + + if (!clientId) { + clientId = 'client_01HNM792M5G5G1A2THWPXKFMXB'; + logDebug(`Using fixed client ID: ${clientId}`); + } + + logInfo('Refreshing API key...'); + + try { + // Create form data + const formData = new URLSearchParams(); + formData.append('grant_type', 'refresh_token'); + formData.append('refresh_token', currentRefreshToken); + formData.append('client_id', clientId); + + const response = await fetch(REFRESH_URL, { + method: 'POST', + headers: { + 'Content-Type': 'application/x-www-form-urlencoded' + }, + body: formData.toString() + }); + + if (!response.ok) { + const errorText = await response.text(); + throw new Error(`Failed to refresh token: ${response.status} ${errorText}`); + } + + const data = await response.json(); + + // Update tokens + currentApiKey = data.access_token; + currentRefreshToken = data.refresh_token; + lastRefreshTime = Date.now(); + + // Log user info + if (data.user) { + logInfo(`Authenticated as: ${data.user.email} (${data.user.first_name} ${data.user.last_name})`); + logInfo(`User ID: ${data.user.id}`); + logInfo(`Organization ID: ${data.organization_id}`); + } + + // Save tokens to file + saveTokens(data.access_token, data.refresh_token); + + logInfo('API key refreshed successfully'); + return data.access_token; + + } catch (error) { + logError('Failed to refresh API key', error); + throw error; + } +} + +/** + * Save tokens to appropriate file + */ +function saveTokens(accessToken, refreshToken) { + try { + const authData = { + access_token: accessToken, + refresh_token: refreshToken, + last_updated: new Date().toISOString() + }; + + // Ensure directory exists + const dir = path.dirname(authFilePath); + if (!fs.existsSync(dir)) { + fs.mkdirSync(dir, { recursive: true }); + } + + // If saving to ~/.factory/auth.json, preserve other fields + if (authSource === 'file' && fs.existsSync(authFilePath)) { + try { + const existingData = JSON.parse(fs.readFileSync(authFilePath, 'utf-8')); + Object.assign(authData, existingData, { + access_token: accessToken, + refresh_token: refreshToken, + last_updated: authData.last_updated + }); + } catch (error) { + logError('Error reading existing auth file, will overwrite', error); + } + } + + fs.writeFileSync(authFilePath, JSON.stringify(authData, null, 2), 'utf-8'); + logDebug(`Tokens saved to ${authFilePath}`); + + } catch (error) { + logError('Failed to save tokens', error); + } +} + +/** + * Check if API key needs refresh (older than 6 hours) + */ +function shouldRefresh() { + if (!lastRefreshTime) { + return true; + } + + const hoursSinceRefresh = (Date.now() - lastRefreshTime) / (1000 * 60 * 60); + return hoursSinceRefresh >= REFRESH_INTERVAL_HOURS; +} + +/** + * Initialize auth system - load refresh token and get initial API key + */ +export async function initializeAuth() { + try { + currentRefreshToken = loadRefreshToken(); + + // Always refresh on startup to get fresh token + await refreshApiKey(); + + logInfo('Auth system initialized successfully'); + } catch (error) { + logError('Failed to initialize auth system', error); + throw error; + } +} + +/** + * Get API key, refresh if needed + */ +export async function getApiKey() { + // Check if we need to refresh + if (shouldRefresh()) { + logInfo('API key needs refresh (6+ hours old)'); + await refreshApiKey(); + } + + if (!currentApiKey) { + throw new Error('No API key available. Please initialize auth system first.'); + } + + return `Bearer ${currentApiKey}`; +} diff --git a/config.js b/config.js new file mode 100644 index 0000000..d1a7119 --- /dev/null +++ b/config.js @@ -0,0 +1,46 @@ +import fs from 'fs'; +import path from 'path'; +import { fileURLToPath } from 'url'; + +const __filename = fileURLToPath(import.meta.url); +const __dirname = path.dirname(__filename); + +let config = null; + +export function loadConfig() { + try { + const configPath = path.join(__dirname, 'config.json'); + const configData = fs.readFileSync(configPath, 'utf-8'); + config = JSON.parse(configData); + return config; + } catch (error) { + throw new Error(`Failed to load config.json: ${error.message}`); + } +} + +export function getConfig() { + if (!config) { + loadConfig(); + } + return config; +} + +export function getModelById(modelId) { + const cfg = getConfig(); + return cfg.models.find(m => m.id === modelId); +} + +export function getEndpointByType(type) { + const cfg = getConfig(); + return cfg.endpoint.find(e => e.name === type); +} + +export function isDevMode() { + const cfg = getConfig(); + return cfg.dev_mode === true; +} + +export function getPort() { + const cfg = getConfig(); + return cfg.port || 3000; +} diff --git a/config.json b/config.json new file mode 100644 index 0000000..24ad81b --- /dev/null +++ b/config.json @@ -0,0 +1,41 @@ +{ + "port": 3000, + "endpoint": [ + { + "name": "openai", + "base_url": "https://app.factory.ai/api/llm/o/v1/responses" + }, + { + "name": "anthropic", + "base_url": "https://app.factory.ai/api/llm/a/v1/messages" + } + ], + "models": [ + { + "name": "Opus 4.1", + "id": "claude-opus-4-1-20250805", + "type": "anthropic" + }, + { + "name": "Sonnet 4", + "id": "claude-sonnet-4-20250514", + "type": "anthropic" + }, + { + "name": "Sonnet 4.5", + "id": "claude-sonnet-4-5-20250929", + "type": "anthropic" + }, + { + "name": "GPT-5", + "id": "gpt-5-2025-08-07", + "type": "openai" + }, + { + "name": "GPT-5-Codex", + "id": "gpt-5-codex", + "type": "openai" + } + ], + "dev_mode": false +} diff --git a/logger.js b/logger.js new file mode 100644 index 0000000..fb400bc --- /dev/null +++ b/logger.js @@ -0,0 +1,60 @@ +import { isDevMode } from './config.js'; + +export function logInfo(message, data = null) { + console.log(`[INFO] ${message}`); + if (data && isDevMode()) { + console.log(JSON.stringify(data, null, 2)); + } +} + +export function logDebug(message, data = null) { + if (isDevMode()) { + console.log(`[DEBUG] ${message}`); + if (data) { + console.log(JSON.stringify(data, null, 2)); + } + } +} + +export function logError(message, error = null) { + console.error(`[ERROR] ${message}`); + if (error) { + if (isDevMode()) { + console.error(error); + } else { + console.error(error.message || error); + } + } +} + +export function logRequest(method, url, headers = null, body = null) { + if (isDevMode()) { + console.log(`\n${'='.repeat(80)}`); + console.log(`[REQUEST] ${method} ${url}`); + if (headers) { + console.log('[HEADERS]', JSON.stringify(headers, null, 2)); + } + if (body) { + console.log('[BODY]', JSON.stringify(body, null, 2)); + } + console.log('='.repeat(80) + '\n'); + } else { + console.log(`[REQUEST] ${method} ${url}`); + } +} + +export function logResponse(status, headers = null, body = null) { + if (isDevMode()) { + console.log(`\n${'-'.repeat(80)}`); + console.log(`[RESPONSE] Status: ${status}`); + if (headers) { + console.log('[HEADERS]', JSON.stringify(headers, null, 2)); + } + if (body) { + console.log('[BODY]', JSON.stringify(body, null, 2)); + } + console.log('-'.repeat(80) + '\n'); + } else { + console.log(`[RESPONSE] Status: ${status}`); + } +} diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 0000000..142a22f --- /dev/null +++ b/package-lock.json @@ -0,0 +1,925 @@ +{ + "name": "droid2api", + "version": "1.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "droid2api", + "version": "1.0.0", + "license": "MIT", + "dependencies": { + "express": "^4.18.2", + "node-fetch": "^3.3.2" + } + }, + "node_modules/accepts": { + "version": "1.3.8", + "resolved": "https://registry.npmmirror.com/accepts/-/accepts-1.3.8.tgz", + "integrity": "sha512-PYAthTa2m2VKxuvSD3DPC/Gy+U+sOA1LAuT8mkmRuvw+NACSaeXEQ+NHcVF7rONl6qcaxV3Uuemwawk+7+SJLw==", + "license": "MIT", + "dependencies": { + "mime-types": "~2.1.34", + "negotiator": "0.6.3" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/array-flatten": { + "version": "1.1.1", + "resolved": "https://registry.npmmirror.com/array-flatten/-/array-flatten-1.1.1.tgz", + "integrity": "sha512-PCVAQswWemu6UdxsDFFX/+gVeYqKAod3D3UVm91jHwynguOwAvYPhx8nNlM++NqRcK6CxxpUafjmhIdKiHibqg==", + "license": "MIT" + }, + "node_modules/body-parser": { + "version": "1.20.3", + "resolved": "https://registry.npmmirror.com/body-parser/-/body-parser-1.20.3.tgz", + "integrity": "sha512-7rAxByjUMqQ3/bHJy7D6OGXvx/MMc4IqBn/X0fcM1QUcAItpZrBEYhWGem+tzXH90c+G01ypMcYJBO9Y30203g==", + "license": "MIT", + "dependencies": { + "bytes": "3.1.2", + "content-type": "~1.0.5", + "debug": "2.6.9", + "depd": "2.0.0", + "destroy": "1.2.0", + "http-errors": "2.0.0", + "iconv-lite": "0.4.24", + "on-finished": "2.4.1", + "qs": "6.13.0", + "raw-body": "2.5.2", + "type-is": "~1.6.18", + "unpipe": "1.0.0" + }, + "engines": { + "node": ">= 0.8", + "npm": "1.2.8000 || >= 1.4.16" + } + }, + "node_modules/bytes": { + "version": "3.1.2", + "resolved": "https://registry.npmmirror.com/bytes/-/bytes-3.1.2.tgz", + "integrity": "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/call-bind-apply-helpers": { + "version": "1.0.2", + "resolved": "https://registry.npmmirror.com/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz", + "integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/call-bound": { + "version": "1.0.4", + "resolved": "https://registry.npmmirror.com/call-bound/-/call-bound-1.0.4.tgz", + "integrity": "sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "get-intrinsic": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/content-disposition": { + "version": "0.5.4", + "resolved": "https://registry.npmmirror.com/content-disposition/-/content-disposition-0.5.4.tgz", + "integrity": "sha512-FveZTNuGw04cxlAiWbzi6zTAL/lhehaWbTtgluJh4/E95DqMwTmha3KZN1aAWA8cFIhHzMZUvLevkw5Rqk+tSQ==", + "license": "MIT", + "dependencies": { + "safe-buffer": "5.2.1" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/content-type": { + "version": "1.0.5", + "resolved": "https://registry.npmmirror.com/content-type/-/content-type-1.0.5.tgz", + "integrity": "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/cookie": { + "version": "0.7.1", + "resolved": "https://registry.npmmirror.com/cookie/-/cookie-0.7.1.tgz", + "integrity": "sha512-6DnInpx7SJ2AK3+CTUE/ZM0vWTUboZCegxhC2xiIydHR9jNuTAASBrfEpHhiGOZw/nX51bHt6YQl8jsGo4y/0w==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/cookie-signature": { + "version": "1.0.6", + "resolved": "https://registry.npmmirror.com/cookie-signature/-/cookie-signature-1.0.6.tgz", + "integrity": "sha512-QADzlaHc8icV8I7vbaJXJwod9HWYp8uCqf1xa4OfNu1T7JVxQIrUgOWtHdNDtPiywmFbiS12VjotIXLrKM3orQ==", + "license": "MIT" + }, + "node_modules/data-uri-to-buffer": { + "version": "4.0.1", + "resolved": "https://registry.npmmirror.com/data-uri-to-buffer/-/data-uri-to-buffer-4.0.1.tgz", + "integrity": "sha512-0R9ikRb668HB7QDxT1vkpuUBtqc53YyAwMwGeUFKRojY/NWKvdZ+9UYtRfGmhqNbRkTSVpMbmyhXipFFv2cb/A==", + "license": "MIT", + "engines": { + "node": ">= 12" + } + }, + "node_modules/debug": { + "version": "2.6.9", + "resolved": "https://registry.npmmirror.com/debug/-/debug-2.6.9.tgz", + "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "license": "MIT", + "dependencies": { + "ms": "2.0.0" + } + }, + "node_modules/depd": { + "version": "2.0.0", + "resolved": "https://registry.npmmirror.com/depd/-/depd-2.0.0.tgz", + "integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/destroy": { + "version": "1.2.0", + "resolved": "https://registry.npmmirror.com/destroy/-/destroy-1.2.0.tgz", + "integrity": "sha512-2sJGJTaXIIaR1w4iJSNoN0hnMY7Gpc/n8D4qSCJw8QqFWXf7cuAgnEHxBpweaVcPevC2l3KpjYCx3NypQQgaJg==", + "license": "MIT", + "engines": { + "node": ">= 0.8", + "npm": "1.2.8000 || >= 1.4.16" + } + }, + "node_modules/dunder-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmmirror.com/dunder-proto/-/dunder-proto-1.0.1.tgz", + "integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.1", + "es-errors": "^1.3.0", + "gopd": "^1.2.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/ee-first": { + "version": "1.1.1", + "resolved": "https://registry.npmmirror.com/ee-first/-/ee-first-1.1.1.tgz", + "integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==", + "license": "MIT" + }, + "node_modules/encodeurl": { + "version": "2.0.0", + "resolved": "https://registry.npmmirror.com/encodeurl/-/encodeurl-2.0.0.tgz", + "integrity": "sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/es-define-property": { + "version": "1.0.1", + "resolved": "https://registry.npmmirror.com/es-define-property/-/es-define-property-1.0.1.tgz", + "integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-errors": { + "version": "1.3.0", + "resolved": "https://registry.npmmirror.com/es-errors/-/es-errors-1.3.0.tgz", + "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-object-atoms": { + "version": "1.1.1", + "resolved": "https://registry.npmmirror.com/es-object-atoms/-/es-object-atoms-1.1.1.tgz", + "integrity": "sha512-FGgH2h8zKNim9ljj7dankFPcICIK9Cp5bm+c2gQSYePhpaG5+esrLODihIorn+Pe6FGJzWhXQotPv73jTaldXA==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/escape-html": { + "version": "1.0.3", + "resolved": "https://registry.npmmirror.com/escape-html/-/escape-html-1.0.3.tgz", + "integrity": "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==", + "license": "MIT" + }, + "node_modules/etag": { + "version": "1.8.1", + "resolved": "https://registry.npmmirror.com/etag/-/etag-1.8.1.tgz", + "integrity": "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/express": { + "version": "4.21.2", + "resolved": "https://registry.npmmirror.com/express/-/express-4.21.2.tgz", + "integrity": "sha512-28HqgMZAmih1Czt9ny7qr6ek2qddF4FclbMzwhCREB6OFfH+rXAnuNCwo1/wFvrtbgsQDb4kSbX9de9lFbrXnA==", + "license": "MIT", + "dependencies": { + "accepts": "~1.3.8", + "array-flatten": "1.1.1", + "body-parser": "1.20.3", + "content-disposition": "0.5.4", + "content-type": "~1.0.4", + "cookie": "0.7.1", + "cookie-signature": "1.0.6", + "debug": "2.6.9", + "depd": "2.0.0", + "encodeurl": "~2.0.0", + "escape-html": "~1.0.3", + "etag": "~1.8.1", + "finalhandler": "1.3.1", + "fresh": "0.5.2", + "http-errors": "2.0.0", + "merge-descriptors": "1.0.3", + "methods": "~1.1.2", + "on-finished": "2.4.1", + "parseurl": "~1.3.3", + "path-to-regexp": "0.1.12", + "proxy-addr": "~2.0.7", + "qs": "6.13.0", + "range-parser": "~1.2.1", + "safe-buffer": "5.2.1", + "send": "0.19.0", + "serve-static": "1.16.2", + "setprototypeof": "1.2.0", + "statuses": "2.0.1", + "type-is": "~1.6.18", + "utils-merge": "1.0.1", + "vary": "~1.1.2" + }, + "engines": { + "node": ">= 0.10.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/fetch-blob": { + "version": "3.2.0", + "resolved": "https://registry.npmmirror.com/fetch-blob/-/fetch-blob-3.2.0.tgz", + "integrity": "sha512-7yAQpD2UMJzLi1Dqv7qFYnPbaPx7ZfFK6PiIxQ4PfkGPyNyl2Ugx+a/umUonmKqjhM4DnfbMvdX6otXq83soQQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/jimmywarting" + }, + { + "type": "paypal", + "url": "https://paypal.me/jimmywarting" + } + ], + "license": "MIT", + "dependencies": { + "node-domexception": "^1.0.0", + "web-streams-polyfill": "^3.0.3" + }, + "engines": { + "node": "^12.20 || >= 14.13" + } + }, + "node_modules/finalhandler": { + "version": "1.3.1", + "resolved": "https://registry.npmmirror.com/finalhandler/-/finalhandler-1.3.1.tgz", + "integrity": "sha512-6BN9trH7bp3qvnrRyzsBz+g3lZxTNZTbVO2EV1CS0WIcDbawYVdYvGflME/9QP0h0pYlCDBCTjYa9nZzMDpyxQ==", + "license": "MIT", + "dependencies": { + "debug": "2.6.9", + "encodeurl": "~2.0.0", + "escape-html": "~1.0.3", + "on-finished": "2.4.1", + "parseurl": "~1.3.3", + "statuses": "2.0.1", + "unpipe": "~1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/formdata-polyfill": { + "version": "4.0.10", + "resolved": "https://registry.npmmirror.com/formdata-polyfill/-/formdata-polyfill-4.0.10.tgz", + "integrity": "sha512-buewHzMvYL29jdeQTVILecSaZKnt/RJWjoZCF5OW60Z67/GmSLBkOFM7qh1PI3zFNtJbaZL5eQu1vLfazOwj4g==", + "license": "MIT", + "dependencies": { + "fetch-blob": "^3.1.2" + }, + "engines": { + "node": ">=12.20.0" + } + }, + "node_modules/forwarded": { + "version": "0.2.0", + "resolved": "https://registry.npmmirror.com/forwarded/-/forwarded-0.2.0.tgz", + "integrity": "sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/fresh": { + "version": "0.5.2", + "resolved": "https://registry.npmmirror.com/fresh/-/fresh-0.5.2.tgz", + "integrity": "sha512-zJ2mQYM18rEFOudeV4GShTGIQ7RbzA7ozbU9I/XBpm7kqgMywgmylMwXHxZJmkVoYkna9d2pVXVXPdYTP9ej8Q==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/function-bind": { + "version": "1.1.2", + "resolved": "https://registry.npmmirror.com/function-bind/-/function-bind-1.1.2.tgz", + "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-intrinsic": { + "version": "1.3.0", + "resolved": "https://registry.npmmirror.com/get-intrinsic/-/get-intrinsic-1.3.0.tgz", + "integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "es-define-property": "^1.0.1", + "es-errors": "^1.3.0", + "es-object-atoms": "^1.1.1", + "function-bind": "^1.1.2", + "get-proto": "^1.0.1", + "gopd": "^1.2.0", + "has-symbols": "^1.1.0", + "hasown": "^2.0.2", + "math-intrinsics": "^1.1.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmmirror.com/get-proto/-/get-proto-1.0.1.tgz", + "integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==", + "license": "MIT", + "dependencies": { + "dunder-proto": "^1.0.1", + "es-object-atoms": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/gopd": { + "version": "1.2.0", + "resolved": "https://registry.npmmirror.com/gopd/-/gopd-1.2.0.tgz", + "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-symbols": { + "version": "1.1.0", + "resolved": "https://registry.npmmirror.com/has-symbols/-/has-symbols-1.1.0.tgz", + "integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/hasown": { + "version": "2.0.2", + "resolved": "https://registry.npmmirror.com/hasown/-/hasown-2.0.2.tgz", + "integrity": "sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==", + "license": "MIT", + "dependencies": { + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/http-errors": { + "version": "2.0.0", + "resolved": "https://registry.npmmirror.com/http-errors/-/http-errors-2.0.0.tgz", + "integrity": "sha512-FtwrG/euBzaEjYeRqOgly7G0qviiXoJWnvEH2Z1plBdXgbyjv34pHTSb9zoeHMyDy33+DWy5Wt9Wo+TURtOYSQ==", + "license": "MIT", + "dependencies": { + "depd": "2.0.0", + "inherits": "2.0.4", + "setprototypeof": "1.2.0", + "statuses": "2.0.1", + "toidentifier": "1.0.1" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/iconv-lite": { + "version": "0.4.24", + "resolved": "https://registry.npmmirror.com/iconv-lite/-/iconv-lite-0.4.24.tgz", + "integrity": "sha512-v3MXnZAcvnywkTUEZomIActle7RXXeedOR31wwl7VlyoXO4Qi9arvSenNQWne1TcRwhCL1HwLI21bEqdpj8/rA==", + "license": "MIT", + "dependencies": { + "safer-buffer": ">= 2.1.2 < 3" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/inherits": { + "version": "2.0.4", + "resolved": "https://registry.npmmirror.com/inherits/-/inherits-2.0.4.tgz", + "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", + "license": "ISC" + }, + "node_modules/ipaddr.js": { + "version": "1.9.1", + "resolved": "https://registry.npmmirror.com/ipaddr.js/-/ipaddr.js-1.9.1.tgz", + "integrity": "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==", + "license": "MIT", + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/math-intrinsics": { + "version": "1.1.0", + "resolved": "https://registry.npmmirror.com/math-intrinsics/-/math-intrinsics-1.1.0.tgz", + "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/media-typer": { + "version": "0.3.0", + "resolved": "https://registry.npmmirror.com/media-typer/-/media-typer-0.3.0.tgz", + "integrity": "sha512-dq+qelQ9akHpcOl/gUVRTxVIOkAJ1wR3QAvb4RsVjS8oVoFjDGTc679wJYmUmknUF5HwMLOgb5O+a3KxfWapPQ==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/merge-descriptors": { + "version": "1.0.3", + "resolved": "https://registry.npmmirror.com/merge-descriptors/-/merge-descriptors-1.0.3.tgz", + "integrity": "sha512-gaNvAS7TZ897/rVaZ0nMtAyxNyi/pdbjbAwUpFQpN70GqnVfOiXpeUUMKRBmzXaSQ8DdTX4/0ms62r2K+hE6mQ==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/methods": { + "version": "1.1.2", + "resolved": "https://registry.npmmirror.com/methods/-/methods-1.1.2.tgz", + "integrity": "sha512-iclAHeNqNm68zFtnZ0e+1L2yUIdvzNoauKU4WBA3VvH/vPFieF7qfRlwUZU+DA9P9bPXIS90ulxoUoCH23sV2w==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mime": { + "version": "1.6.0", + "resolved": "https://registry.npmmirror.com/mime/-/mime-1.6.0.tgz", + "integrity": "sha512-x0Vn8spI+wuJ1O6S7gnbaQg8Pxh4NNHb7KSINmEWKiPE4RKOplvijn+NkmYmmRgP68mc70j2EbeTFRsrswaQeg==", + "license": "MIT", + "bin": { + "mime": "cli.js" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/mime-db": { + "version": "1.52.0", + "resolved": "https://registry.npmmirror.com/mime-db/-/mime-db-1.52.0.tgz", + "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mime-types": { + "version": "2.1.35", + "resolved": "https://registry.npmmirror.com/mime-types/-/mime-types-2.1.35.tgz", + "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==", + "license": "MIT", + "dependencies": { + "mime-db": "1.52.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/ms": { + "version": "2.0.0", + "resolved": "https://registry.npmmirror.com/ms/-/ms-2.0.0.tgz", + "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==", + "license": "MIT" + }, + "node_modules/negotiator": { + "version": "0.6.3", + "resolved": "https://registry.npmmirror.com/negotiator/-/negotiator-0.6.3.tgz", + "integrity": "sha512-+EUsqGPLsM+j/zdChZjsnX51g4XrHFOIXwfnCVPGlQk/k5giakcKsuxCObBRu6DSm9opw/O6slWbJdghQM4bBg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/node-domexception": { + "version": "1.0.0", + "resolved": "https://registry.npmmirror.com/node-domexception/-/node-domexception-1.0.0.tgz", + "integrity": "sha512-/jKZoMpw0F8GRwl4/eLROPA3cfcXtLApP0QzLmUT/HuPCZWyB7IY9ZrMeKw2O/nFIqPQB3PVM9aYm0F312AXDQ==", + "deprecated": "Use your platform's native DOMException instead", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/jimmywarting" + }, + { + "type": "github", + "url": "https://paypal.me/jimmywarting" + } + ], + "license": "MIT", + "engines": { + "node": ">=10.5.0" + } + }, + "node_modules/node-fetch": { + "version": "3.3.2", + "resolved": "https://registry.npmmirror.com/node-fetch/-/node-fetch-3.3.2.tgz", + "integrity": "sha512-dRB78srN/l6gqWulah9SrxeYnxeddIG30+GOqK/9OlLVyLg3HPnr6SqOWTWOXKRwC2eGYCkZ59NNuSgvSrpgOA==", + "license": "MIT", + "dependencies": { + "data-uri-to-buffer": "^4.0.0", + "fetch-blob": "^3.1.4", + "formdata-polyfill": "^4.0.10" + }, + "engines": { + "node": "^12.20.0 || ^14.13.1 || >=16.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/node-fetch" + } + }, + "node_modules/object-inspect": { + "version": "1.13.4", + "resolved": "https://registry.npmmirror.com/object-inspect/-/object-inspect-1.13.4.tgz", + "integrity": "sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/on-finished": { + "version": "2.4.1", + "resolved": "https://registry.npmmirror.com/on-finished/-/on-finished-2.4.1.tgz", + "integrity": "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg==", + "license": "MIT", + "dependencies": { + "ee-first": "1.1.1" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/parseurl": { + "version": "1.3.3", + "resolved": "https://registry.npmmirror.com/parseurl/-/parseurl-1.3.3.tgz", + "integrity": "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/path-to-regexp": { + "version": "0.1.12", + "resolved": "https://registry.npmmirror.com/path-to-regexp/-/path-to-regexp-0.1.12.tgz", + "integrity": "sha512-RA1GjUVMnvYFxuqovrEqZoxxW5NUZqbwKtYz/Tt7nXerk0LbLblQmrsgdeOxV5SFHf0UDggjS/bSeOZwt1pmEQ==", + "license": "MIT" + }, + "node_modules/proxy-addr": { + "version": "2.0.7", + "resolved": "https://registry.npmmirror.com/proxy-addr/-/proxy-addr-2.0.7.tgz", + "integrity": "sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg==", + "license": "MIT", + "dependencies": { + "forwarded": "0.2.0", + "ipaddr.js": "1.9.1" + }, + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/qs": { + "version": "6.13.0", + "resolved": "https://registry.npmmirror.com/qs/-/qs-6.13.0.tgz", + "integrity": "sha512-+38qI9SOr8tfZ4QmJNplMUxqjbe7LKvvZgWdExBOmd+egZTtjLB67Gu0HRX3u/XOq7UU2Nx6nsjvS16Z9uwfpg==", + "license": "BSD-3-Clause", + "dependencies": { + "side-channel": "^1.0.6" + }, + "engines": { + "node": ">=0.6" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/range-parser": { + "version": "1.2.1", + "resolved": "https://registry.npmmirror.com/range-parser/-/range-parser-1.2.1.tgz", + "integrity": "sha512-Hrgsx+orqoygnmhFbKaHE6c296J+HTAQXoxEF6gNupROmmGJRoyzfG3ccAveqCBrwr/2yxQ5BVd/GTl5agOwSg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/raw-body": { + "version": "2.5.2", + "resolved": "https://registry.npmmirror.com/raw-body/-/raw-body-2.5.2.tgz", + "integrity": "sha512-8zGqypfENjCIqGhgXToC8aB2r7YrBX+AQAfIPs/Mlk+BtPTztOvTS01NRW/3Eh60J+a48lt8qsCzirQ6loCVfA==", + "license": "MIT", + "dependencies": { + "bytes": "3.1.2", + "http-errors": "2.0.0", + "iconv-lite": "0.4.24", + "unpipe": "1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/safe-buffer": { + "version": "5.2.1", + "resolved": "https://registry.npmmirror.com/safe-buffer/-/safe-buffer-5.2.1.tgz", + "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT" + }, + "node_modules/safer-buffer": { + "version": "2.1.2", + "resolved": "https://registry.npmmirror.com/safer-buffer/-/safer-buffer-2.1.2.tgz", + "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==", + "license": "MIT" + }, + "node_modules/send": { + "version": "0.19.0", + "resolved": "https://registry.npmmirror.com/send/-/send-0.19.0.tgz", + "integrity": "sha512-dW41u5VfLXu8SJh5bwRmyYUbAoSB3c9uQh6L8h/KtsFREPWpbX1lrljJo186Jc4nmci/sGUZ9a0a0J2zgfq2hw==", + "license": "MIT", + "dependencies": { + "debug": "2.6.9", + "depd": "2.0.0", + "destroy": "1.2.0", + "encodeurl": "~1.0.2", + "escape-html": "~1.0.3", + "etag": "~1.8.1", + "fresh": "0.5.2", + "http-errors": "2.0.0", + "mime": "1.6.0", + "ms": "2.1.3", + "on-finished": "2.4.1", + "range-parser": "~1.2.1", + "statuses": "2.0.1" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/send/node_modules/encodeurl": { + "version": "1.0.2", + "resolved": "https://registry.npmmirror.com/encodeurl/-/encodeurl-1.0.2.tgz", + "integrity": "sha512-TPJXq8JqFaVYm2CWmPvnP2Iyo4ZSM7/QKcSmuMLDObfpH5fi7RUGmd/rTDf+rut/saiDiQEeVTNgAmJEdAOx0w==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/send/node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmmirror.com/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "license": "MIT" + }, + "node_modules/serve-static": { + "version": "1.16.2", + "resolved": "https://registry.npmmirror.com/serve-static/-/serve-static-1.16.2.tgz", + "integrity": "sha512-VqpjJZKadQB/PEbEwvFdO43Ax5dFBZ2UECszz8bQ7pi7wt//PWe1P6MN7eCnjsatYtBT6EuiClbjSWP2WrIoTw==", + "license": "MIT", + "dependencies": { + "encodeurl": "~2.0.0", + "escape-html": "~1.0.3", + "parseurl": "~1.3.3", + "send": "0.19.0" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/setprototypeof": { + "version": "1.2.0", + "resolved": "https://registry.npmmirror.com/setprototypeof/-/setprototypeof-1.2.0.tgz", + "integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==", + "license": "ISC" + }, + "node_modules/side-channel": { + "version": "1.1.0", + "resolved": "https://registry.npmmirror.com/side-channel/-/side-channel-1.1.0.tgz", + "integrity": "sha512-ZX99e6tRweoUXqR+VBrslhda51Nh5MTQwou5tnUDgbtyM0dBgmhEDtWGP/xbKn6hqfPRHujUNwz5fy/wbbhnpw==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "object-inspect": "^1.13.3", + "side-channel-list": "^1.0.0", + "side-channel-map": "^1.0.1", + "side-channel-weakmap": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-list": { + "version": "1.0.0", + "resolved": "https://registry.npmmirror.com/side-channel-list/-/side-channel-list-1.0.0.tgz", + "integrity": "sha512-FCLHtRD/gnpCiCHEiJLOwdmFP+wzCmDEkc9y7NsYxeF4u7Btsn1ZuwgwJGxImImHicJArLP4R0yX4c2KCrMrTA==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "object-inspect": "^1.13.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-map": { + "version": "1.0.1", + "resolved": "https://registry.npmmirror.com/side-channel-map/-/side-channel-map-1.0.1.tgz", + "integrity": "sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA==", + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.5", + "object-inspect": "^1.13.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-weakmap": { + "version": "1.0.2", + "resolved": "https://registry.npmmirror.com/side-channel-weakmap/-/side-channel-weakmap-1.0.2.tgz", + "integrity": "sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A==", + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.5", + "object-inspect": "^1.13.3", + "side-channel-map": "^1.0.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/statuses": { + "version": "2.0.1", + "resolved": "https://registry.npmmirror.com/statuses/-/statuses-2.0.1.tgz", + "integrity": "sha512-RwNA9Z/7PrK06rYLIzFMlaF+l73iwpzsqRIFgbMLbTcLD6cOao82TaWefPXQvB2fOC4AjuYSEndS7N/mTCbkdQ==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/toidentifier": { + "version": "1.0.1", + "resolved": "https://registry.npmmirror.com/toidentifier/-/toidentifier-1.0.1.tgz", + "integrity": "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==", + "license": "MIT", + "engines": { + "node": ">=0.6" + } + }, + "node_modules/type-is": { + "version": "1.6.18", + "resolved": "https://registry.npmmirror.com/type-is/-/type-is-1.6.18.tgz", + "integrity": "sha512-TkRKr9sUTxEH8MdfuCSP7VizJyzRNMjj2J2do2Jr3Kym598JVdEksuzPQCnlFPW4ky9Q+iA+ma9BGm06XQBy8g==", + "license": "MIT", + "dependencies": { + "media-typer": "0.3.0", + "mime-types": "~2.1.24" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/unpipe": { + "version": "1.0.0", + "resolved": "https://registry.npmmirror.com/unpipe/-/unpipe-1.0.0.tgz", + "integrity": "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/utils-merge": { + "version": "1.0.1", + "resolved": "https://registry.npmmirror.com/utils-merge/-/utils-merge-1.0.1.tgz", + "integrity": "sha512-pMZTvIkT1d+TFGvDOqodOclx0QWkkgi6Tdoa8gC8ffGAAqz9pzPTZWAybbsHHoED/ztMtkv/VoYTYyShUn81hA==", + "license": "MIT", + "engines": { + "node": ">= 0.4.0" + } + }, + "node_modules/vary": { + "version": "1.1.2", + "resolved": "https://registry.npmmirror.com/vary/-/vary-1.1.2.tgz", + "integrity": "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/web-streams-polyfill": { + "version": "3.3.3", + "resolved": "https://registry.npmmirror.com/web-streams-polyfill/-/web-streams-polyfill-3.3.3.tgz", + "integrity": "sha512-d2JWLCivmZYTSIoge9MsgFCZrt571BikcWGYkjC1khllbTeDlGqZ2D8vD8E/lJa8WGWbb7Plm8/XJYV7IJHZZw==", + "license": "MIT", + "engines": { + "node": ">= 8" + } + } + } +} diff --git a/package.json b/package.json new file mode 100644 index 0000000..46707a7 --- /dev/null +++ b/package.json @@ -0,0 +1,18 @@ +{ + "name": "droid2api", + "version": "1.0.0", + "description": "OpenAI Compatible API Proxy", + "main": "server.js", + "type": "module", + "scripts": { + "start": "node server.js", + "dev": "node server.js" + }, + "keywords": ["openai", "api", "proxy"], + "author": "", + "license": "MIT", + "dependencies": { + "express": "^4.18.2", + "node-fetch": "^3.3.2" + } +} diff --git a/routes.js b/routes.js new file mode 100644 index 0000000..189ba7e --- /dev/null +++ b/routes.js @@ -0,0 +1,157 @@ +import express from 'express'; +import fetch from 'node-fetch'; +import { getConfig, getModelById, getEndpointByType } from './config.js'; +import { logInfo, logDebug, logError, logRequest, logResponse } from './logger.js'; +import { transformToAnthropic, getAnthropicHeaders } from './transformers/request-anthropic.js'; +import { transformToOpenAI, getOpenAIHeaders } from './transformers/request-openai.js'; +import { AnthropicResponseTransformer } from './transformers/response-anthropic.js'; +import { OpenAIResponseTransformer } from './transformers/response-openai.js'; +import { getApiKey } from './auth.js'; + +const router = express.Router(); + +router.get('/v1/models', (req, res) => { + logInfo('GET /v1/models'); + + try { + const config = getConfig(); + const models = config.models.map(model => ({ + id: model.id, + object: 'model', + created: Date.now(), + owned_by: model.type, + permission: [], + root: model.id, + parent: null + })); + + const response = { + object: 'list', + data: models + }; + + logResponse(200, null, response); + res.json(response); + } catch (error) { + logError('Error in GET /v1/models', error); + res.status(500).json({ error: 'Internal server error' }); + } +}); + +router.post('/v1/chat/completions', async (req, res) => { + logInfo('POST /v1/chat/completions'); + + try { + const openaiRequest = req.body; + const modelId = openaiRequest.model; + + if (!modelId) { + return res.status(400).json({ error: 'model is required' }); + } + + const model = getModelById(modelId); + if (!model) { + return res.status(404).json({ error: `Model ${modelId} not found` }); + } + + const endpoint = getEndpointByType(model.type); + if (!endpoint) { + return res.status(500).json({ error: `Endpoint type ${model.type} not found` }); + } + + logInfo(`Routing to ${model.type} endpoint: ${endpoint.base_url}`); + + // Get API key (will auto-refresh if needed) + let authHeader; + try { + authHeader = await getApiKey(); + } catch (error) { + logError('Failed to get API key', error); + return res.status(500).json({ + error: 'API key not available', + message: 'Failed to get or refresh API key. Please check server logs.' + }); + } + + let transformedRequest; + let headers; + const clientHeaders = req.headers; + + // Log received client headers for debugging + logDebug('Client headers received', { + 'x-factory-client': clientHeaders['x-factory-client'], + 'x-session-id': clientHeaders['x-session-id'], + 'x-assistant-message-id': clientHeaders['x-assistant-message-id'], + 'user-agent': clientHeaders['user-agent'] + }); + + if (model.type === 'anthropic') { + transformedRequest = transformToAnthropic(openaiRequest); + const isStreaming = openaiRequest.stream !== false; + headers = getAnthropicHeaders(authHeader, clientHeaders, isStreaming); + } else if (model.type === 'openai') { + transformedRequest = transformToOpenAI(openaiRequest); + headers = getOpenAIHeaders(authHeader, clientHeaders); + } else { + return res.status(500).json({ error: `Unknown endpoint type: ${model.type}` }); + } + + logRequest('POST', endpoint.base_url, headers, transformedRequest); + + const response = await fetch(endpoint.base_url, { + method: 'POST', + headers, + body: JSON.stringify(transformedRequest) + }); + + logInfo(`Response status: ${response.status}`); + + if (!response.ok) { + const errorText = await response.text(); + logError(`Endpoint error: ${response.status}`, new Error(errorText)); + return res.status(response.status).json({ + error: `Endpoint returned ${response.status}`, + details: errorText + }); + } + + const isStreaming = transformedRequest.stream !== false; + + if (isStreaming) { + res.setHeader('Content-Type', 'text/event-stream'); + res.setHeader('Cache-Control', 'no-cache'); + res.setHeader('Connection', 'keep-alive'); + + let transformer; + if (model.type === 'anthropic') { + transformer = new AnthropicResponseTransformer(modelId, `chatcmpl-${Date.now()}`); + } else if (model.type === 'openai') { + transformer = new OpenAIResponseTransformer(modelId, `chatcmpl-${Date.now()}`); + } + + try { + for await (const chunk of transformer.transformStream(response.body)) { + res.write(chunk); + } + res.end(); + logInfo('Stream completed'); + } catch (streamError) { + logError('Stream error', streamError); + res.end(); + } + } else { + const data = await response.json(); + logResponse(200, null, data); + res.json(data); + } + + } catch (error) { + logError('Error in POST /v1/chat/completions', error); + res.status(500).json({ + error: 'Internal server error', + message: error.message + }); + } +}); + +export default router; diff --git a/server.js b/server.js new file mode 100644 index 0000000..d0ca0d0 --- /dev/null +++ b/server.js @@ -0,0 +1,86 @@ +import express from 'express'; +import { loadConfig, isDevMode, getPort } from './config.js'; +import { logInfo, logError } from './logger.js'; +import router from './routes.js'; +import { initializeAuth } from './auth.js'; + +const app = express(); + +app.use(express.json({ limit: '50mb' })); +app.use(express.urlencoded({ extended: true, limit: '50mb' })); + +app.use((req, res, next) => { + res.header('Access-Control-Allow-Origin', '*'); + res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS'); + res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization'); + + if (req.method === 'OPTIONS') { + return res.sendStatus(200); + } + next(); +}); + +app.use(router); + +app.get('/', (req, res) => { + res.json({ + name: 'droid2api', + version: '1.0.0', + description: 'OpenAI Compatible API Proxy', + endpoints: [ + 'GET /v1/models', + 'POST /v1/chat/completions' + ] + }); +}); + +app.use((err, req, res, next) => { + logError('Unhandled error', err); + res.status(500).json({ + error: 'Internal server error', + message: isDevMode() ? err.message : undefined + }); +}); + +(async () => { + try { + loadConfig(); + logInfo('Configuration loaded successfully'); + logInfo(`Dev mode: ${isDevMode()}`); + + // Initialize auth system (load and refresh API key) + await initializeAuth(); + + const PORT = getPort(); + logInfo(`Starting server on port ${PORT}...`); + + const server = app.listen(PORT) + .on('listening', () => { + logInfo(`Server running on http://localhost:${PORT}`); + logInfo('Available endpoints:'); + logInfo(' GET /v1/models'); + logInfo(' POST /v1/chat/completions'); + }) + .on('error', (err) => { + if (err.code === 'EADDRINUSE') { + console.error(`\n${'='.repeat(80)}`); + console.error(`ERROR: Port ${PORT} is already in use!`); + console.error(''); + console.error('Please choose one of the following options:'); + console.error(` 1. Stop the process using port ${PORT}:`); + console.error(` lsof -ti:${PORT} | xargs kill`); + console.error(''); + console.error(' 2. Change the port in config.json:'); + console.error(' Edit config.json and modify the "port" field'); + console.error(`${'='.repeat(80)}\n`); + process.exit(1); + } else { + logError('Failed to start server', err); + process.exit(1); + } + }); + } catch (error) { + logError('Failed to start server', error); + process.exit(1); + } +})(); diff --git a/start.sh b/start.sh new file mode 100755 index 0000000..13c444e --- /dev/null +++ b/start.sh @@ -0,0 +1,4 @@ +#!/bin/bash + +echo "Starting droid2api server..." +node server.js diff --git a/transformers/request-anthropic.js b/transformers/request-anthropic.js new file mode 100644 index 0000000..e2b863c --- /dev/null +++ b/transformers/request-anthropic.js @@ -0,0 +1,172 @@ +import { logDebug } from '../logger.js'; + +export function transformToAnthropic(openaiRequest) { + logDebug('Transforming OpenAI request to Anthropic format'); + + const anthropicRequest = { + model: openaiRequest.model, + messages: [], + stream: openaiRequest.stream !== false + }; + + // Handle max_tokens + if (openaiRequest.max_tokens) { + anthropicRequest.max_tokens = openaiRequest.max_tokens; + } else if (openaiRequest.max_completion_tokens) { + anthropicRequest.max_tokens = openaiRequest.max_completion_tokens; + } else { + anthropicRequest.max_tokens = 4096; + } + + // Extract system message(s) and transform other messages + let systemContent = []; + + if (openaiRequest.messages && Array.isArray(openaiRequest.messages)) { + for (const msg of openaiRequest.messages) { + // Handle system messages separately + if (msg.role === 'system') { + if (typeof msg.content === 'string') { + systemContent.push({ + type: 'text', + text: msg.content + }); + } else if (Array.isArray(msg.content)) { + for (const part of msg.content) { + if (part.type === 'text') { + systemContent.push({ + type: 'text', + text: part.text + }); + } else { + systemContent.push(part); + } + } + } + continue; // Skip adding system messages to messages array + } + + const anthropicMsg = { + role: msg.role, + content: [] + }; + + if (typeof msg.content === 'string') { + anthropicMsg.content.push({ + type: 'text', + text: msg.content + }); + } else if (Array.isArray(msg.content)) { + for (const part of msg.content) { + if (part.type === 'text') { + anthropicMsg.content.push({ + type: 'text', + text: part.text + }); + } else if (part.type === 'image_url') { + anthropicMsg.content.push({ + type: 'image', + source: part.image_url + }); + } else { + anthropicMsg.content.push(part); + } + } + } + + anthropicRequest.messages.push(anthropicMsg); + } + } + + // Add system parameter if system content exists + if (systemContent.length > 0) { + anthropicRequest.system = systemContent; + } + + // Transform tools if present + if (openaiRequest.tools && Array.isArray(openaiRequest.tools)) { + anthropicRequest.tools = openaiRequest.tools.map(tool => { + if (tool.type === 'function') { + return { + name: tool.function.name, + description: tool.function.description, + input_schema: tool.function.parameters || {} + }; + } + return tool; + }); + } + + // Pass through other compatible parameters + if (openaiRequest.temperature !== undefined) { + anthropicRequest.temperature = openaiRequest.temperature; + } + if (openaiRequest.top_p !== undefined) { + anthropicRequest.top_p = openaiRequest.top_p; + } + if (openaiRequest.stop !== undefined) { + anthropicRequest.stop_sequences = Array.isArray(openaiRequest.stop) + ? openaiRequest.stop + : [openaiRequest.stop]; + } + + logDebug('Transformed Anthropic request', anthropicRequest); + return anthropicRequest; +} + +export function getAnthropicHeaders(authHeader, clientHeaders = {}, isStreaming = true) { + // Generate unique IDs if not provided + const sessionId = clientHeaders['x-session-id'] || generateUUID(); + const messageId = clientHeaders['x-assistant-message-id'] || generateUUID(); + + const headers = { + 'accept': 'application/json', + 'content-type': 'application/json', + 'anthropic-version': '2023-06-01', + 'anthropic-beta': 'interleaved-thinking-2025-05-14', + 'x-api-key': 'placeholder', + 'authorization': authHeader || '', + 'x-model-provider': 'anthropic', + 'x-factory-client': 'cli', + 'x-session-id': sessionId, + 'x-assistant-message-id': messageId, + 'user-agent': 'a$/JS 0.57.0', + 'x-stainless-timeout': '600', + 'connection': 'keep-alive' + }; + + // Pass through Stainless SDK headers with defaults + const stainlessDefaults = { + 'x-stainless-arch': 'x64', + 'x-stainless-lang': 'js', + 'x-stainless-os': 'MacOS', + 'x-stainless-runtime': 'node', + 'x-stainless-retry-count': '0', + 'x-stainless-package-version': '0.57.0', + 'x-stainless-runtime-version': 'v24.3.0' + }; + + // Set helper-method based on streaming + if (isStreaming) { + headers['x-stainless-helper-method'] = 'stream'; + } + + // Copy Stainless headers from client or use defaults + Object.keys(stainlessDefaults).forEach(header => { + headers[header] = clientHeaders[header] || stainlessDefaults[header]; + }); + + // Override timeout from defaults if client provided + if (clientHeaders['x-stainless-timeout']) { + headers['x-stainless-timeout'] = clientHeaders['x-stainless-timeout']; + } + + return headers; +} + +function generateUUID() { + return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) { + const r = Math.random() * 16 | 0; + const v = c == 'x' ? r : (r & 0x3 | 0x8); + return v.toString(16); + }); +} diff --git a/transformers/request-openai.js b/transformers/request-openai.js new file mode 100644 index 0000000..538d9be --- /dev/null +++ b/transformers/request-openai.js @@ -0,0 +1,147 @@ +import { logDebug } from '../logger.js'; + +export function transformToOpenAI(openaiRequest) { + logDebug('Transforming OpenAI request to target OpenAI format'); + + const targetRequest = { + model: openaiRequest.model, + input: [], + store: false, + stream: openaiRequest.stream !== false + }; + + // Transform max_tokens to max_output_tokens + if (openaiRequest.max_tokens) { + targetRequest.max_output_tokens = openaiRequest.max_tokens; + } else if (openaiRequest.max_completion_tokens) { + targetRequest.max_output_tokens = openaiRequest.max_completion_tokens; + } + + // Transform messages to input + if (openaiRequest.messages && Array.isArray(openaiRequest.messages)) { + for (const msg of openaiRequest.messages) { + const inputMsg = { + role: msg.role, + content: [] + }; + + // Determine content type based on role + // user role uses 'input_text', assistant role uses 'output_text' + const textType = msg.role === 'assistant' ? 'output_text' : 'input_text'; + const imageType = msg.role === 'assistant' ? 'output_image' : 'input_image'; + + if (typeof msg.content === 'string') { + inputMsg.content.push({ + type: textType, + text: msg.content + }); + } else if (Array.isArray(msg.content)) { + for (const part of msg.content) { + if (part.type === 'text') { + inputMsg.content.push({ + type: textType, + text: part.text + }); + } else if (part.type === 'image_url') { + inputMsg.content.push({ + type: imageType, + image_url: part.image_url + }); + } else { + // Pass through other types as-is + inputMsg.content.push(part); + } + } + } + + targetRequest.input.push(inputMsg); + } + } + + // Transform tools if present + if (openaiRequest.tools && Array.isArray(openaiRequest.tools)) { + targetRequest.tools = openaiRequest.tools.map(tool => ({ + ...tool, + strict: false + })); + } + + // Extract system message as instructions + const systemMessage = openaiRequest.messages?.find(m => m.role === 'system'); + if (systemMessage) { + if (typeof systemMessage.content === 'string') { + targetRequest.instructions = systemMessage.content; + } else if (Array.isArray(systemMessage.content)) { + targetRequest.instructions = systemMessage.content + .filter(p => p.type === 'text') + .map(p => p.text) + .join('\n'); + } + targetRequest.input = targetRequest.input.filter(m => m.role !== 'system'); + } + + // Pass through other parameters + if (openaiRequest.temperature !== undefined) { + targetRequest.temperature = openaiRequest.temperature; + } + if (openaiRequest.top_p !== undefined) { + targetRequest.top_p = openaiRequest.top_p; + } + if (openaiRequest.presence_penalty !== undefined) { + targetRequest.presence_penalty = openaiRequest.presence_penalty; + } + if (openaiRequest.frequency_penalty !== undefined) { + targetRequest.frequency_penalty = openaiRequest.frequency_penalty; + } + if (openaiRequest.parallel_tool_calls !== undefined) { + targetRequest.parallel_tool_calls = openaiRequest.parallel_tool_calls; + } + + logDebug('Transformed target OpenAI request', targetRequest); + return targetRequest; +} + +export function getOpenAIHeaders(authHeader, clientHeaders = {}) { + // Generate unique IDs if not provided + const sessionId = clientHeaders['x-session-id'] || generateUUID(); + const messageId = clientHeaders['x-assistant-message-id'] || generateUUID(); + + const headers = { + 'content-type': 'application/json', + 'authorization': authHeader || '', + 'x-api-key': 'placeholder', + 'x-factory-client': 'cli', + 'x-session-id': sessionId, + 'x-assistant-message-id': messageId, + 'user-agent': 'cB/JS 5.22.0', + 'connection': 'keep-alive' + }; + + // Pass through Stainless SDK headers with defaults + const stainlessDefaults = { + 'x-stainless-arch': 'x64', + 'x-stainless-lang': 'js', + 'x-stainless-os': 'MacOS', + 'x-stainless-runtime': 'node', + 'x-stainless-retry-count': '0', + 'x-stainless-package-version': '5.22.0', + 'x-stainless-runtime-version': 'v24.3.0' + }; + + // Copy Stainless headers from client or use defaults + Object.keys(stainlessDefaults).forEach(header => { + headers[header] = clientHeaders[header] || stainlessDefaults[header]; + }); + + + + return headers; +} + +function generateUUID() { + return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) { + const r = Math.random() * 16 | 0; + const v = c == 'x' ? r : (r & 0x3 | 0x8); + return v.toString(16); + }); +} diff --git a/transformers/response-anthropic.js b/transformers/response-anthropic.js new file mode 100644 index 0000000..513555c --- /dev/null +++ b/transformers/response-anthropic.js @@ -0,0 +1,138 @@ +import { logDebug } from '../logger.js'; + +export class AnthropicResponseTransformer { + constructor(model, requestId) { + this.model = model; + this.requestId = requestId || `chatcmpl-${Date.now()}`; + this.created = Math.floor(Date.now() / 1000); + this.messageId = null; + this.currentIndex = 0; + } + + parseSSELine(line) { + if (line.startsWith('event:')) { + return { type: 'event', value: line.slice(6).trim() }; + } + if (line.startsWith('data:')) { + const dataStr = line.slice(5).trim(); + try { + return { type: 'data', value: JSON.parse(dataStr) }; + } catch (e) { + return { type: 'data', value: dataStr }; + } + } + return null; + } + + transformEvent(eventType, eventData) { + logDebug(`Anthropic event: ${eventType}`); + + if (eventType === 'message_start') { + this.messageId = eventData.message?.id || this.requestId; + return this.createOpenAIChunk('', 'assistant', false); + } + + if (eventType === 'content_block_start') { + return null; + } + + if (eventType === 'content_block_delta') { + const text = eventData.delta?.text || ''; + return this.createOpenAIChunk(text, null, false); + } + + if (eventType === 'content_block_stop') { + return null; + } + + if (eventType === 'message_delta') { + const stopReason = eventData.delta?.stop_reason; + if (stopReason) { + return this.createOpenAIChunk('', null, true, this.mapStopReason(stopReason)); + } + return null; + } + + if (eventType === 'message_stop') { + return this.createDoneSignal(); + } + + if (eventType === 'ping') { + return null; + } + + return null; + } + + createOpenAIChunk(content, role = null, finish = false, finishReason = null) { + const chunk = { + id: this.requestId, + object: 'chat.completion.chunk', + created: this.created, + model: this.model, + choices: [ + { + index: 0, + delta: {}, + finish_reason: finish ? finishReason : null + } + ] + }; + + if (role) { + chunk.choices[0].delta.role = role; + } + if (content) { + chunk.choices[0].delta.content = content; + } + + return `data: ${JSON.stringify(chunk)}\n\n`; + } + + createDoneSignal() { + return 'data: [DONE]\n\n'; + } + + mapStopReason(anthropicReason) { + const mapping = { + 'end_turn': 'stop', + 'max_tokens': 'length', + 'stop_sequence': 'stop', + 'tool_use': 'tool_calls' + }; + return mapping[anthropicReason] || 'stop'; + } + + async *transformStream(sourceStream) { + let buffer = ''; + let currentEvent = null; + + try { + for await (const chunk of sourceStream) { + buffer += chunk.toString(); + const lines = buffer.split('\n'); + buffer = lines.pop() || ''; + + for (const line of lines) { + if (!line.trim()) continue; + + const parsed = this.parseSSELine(line); + if (!parsed) continue; + + if (parsed.type === 'event') { + currentEvent = parsed.value; + } else if (parsed.type === 'data' && currentEvent) { + const transformed = this.transformEvent(currentEvent, parsed.value); + if (transformed) { + yield transformed; + } + currentEvent = null; + } + } + } + } catch (error) { + logDebug('Error in Anthropic stream transformation', error); + throw error; + } + } +} diff --git a/transformers/response-openai.js b/transformers/response-openai.js new file mode 100644 index 0000000..425e15e --- /dev/null +++ b/transformers/response-openai.js @@ -0,0 +1,127 @@ +import { logDebug } from '../logger.js'; + +export class OpenAIResponseTransformer { + constructor(model, requestId) { + this.model = model; + this.requestId = requestId || `chatcmpl-${Date.now()}`; + this.created = Math.floor(Date.now() / 1000); + } + + parseSSELine(line) { + if (line.startsWith('event:')) { + return { type: 'event', value: line.slice(6).trim() }; + } + if (line.startsWith('data:')) { + const dataStr = line.slice(5).trim(); + try { + return { type: 'data', value: JSON.parse(dataStr) }; + } catch (e) { + return { type: 'data', value: dataStr }; + } + } + return null; + } + + transformEvent(eventType, eventData) { + logDebug(`Target OpenAI event: ${eventType}`); + + if (eventType === 'response.created') { + return this.createOpenAIChunk('', 'assistant', false); + } + + if (eventType === 'response.in_progress') { + return null; + } + + if (eventType === 'response.output_text.delta') { + const text = eventData.delta || eventData.text || ''; + return this.createOpenAIChunk(text, null, false); + } + + if (eventType === 'response.output_text.done') { + return null; + } + + if (eventType === 'response.done') { + const status = eventData.response?.status; + let finishReason = 'stop'; + + if (status === 'completed') { + finishReason = 'stop'; + } else if (status === 'incomplete') { + finishReason = 'length'; + } + + const finalChunk = this.createOpenAIChunk('', null, true, finishReason); + const done = this.createDoneSignal(); + return finalChunk + done; + } + + return null; + } + + createOpenAIChunk(content, role = null, finish = false, finishReason = null) { + const chunk = { + id: this.requestId, + object: 'chat.completion.chunk', + created: this.created, + model: this.model, + choices: [ + { + index: 0, + delta: {}, + finish_reason: finish ? finishReason : null + } + ] + }; + + if (role) { + chunk.choices[0].delta.role = role; + } + if (content) { + chunk.choices[0].delta.content = content; + } + + return `data: ${JSON.stringify(chunk)}\n\n`; + } + + createDoneSignal() { + return 'data: [DONE]\n\n'; + } + + async *transformStream(sourceStream) { + let buffer = ''; + let currentEvent = null; + + try { + for await (const chunk of sourceStream) { + buffer += chunk.toString(); + const lines = buffer.split('\n'); + buffer = lines.pop() || ''; + + for (const line of lines) { + if (!line.trim()) continue; + + const parsed = this.parseSSELine(line); + if (!parsed) continue; + + if (parsed.type === 'event') { + currentEvent = parsed.value; + } else if (parsed.type === 'data' && currentEvent) { + const transformed = this.transformEvent(currentEvent, parsed.value); + if (transformed) { + yield transformed; + } + } + } + } + + if (currentEvent === 'response.done' || currentEvent === 'response.completed') { + yield this.createDoneSignal(); + } + } catch (error) { + logDebug('Error in OpenAI stream transformation', error); + throw error; + } + } +}