mirror of
https://github.com/Nezumi-2711/9router.git
synced 2026-09-22 13:38:31 +00:00
feat: add confbox dependency and refactor TOML parsing in codex settings (#282)
fix: update JSDoc for refreshAndUpdateCredentials return type
This commit is contained in:
@@ -15,6 +15,7 @@
|
|||||||
"@monaco-editor/react": "^4.7.0",
|
"@monaco-editor/react": "^4.7.0",
|
||||||
"@xyflow/react": "^12.10.1",
|
"@xyflow/react": "^12.10.1",
|
||||||
"bcryptjs": "^3.0.3",
|
"bcryptjs": "^3.0.3",
|
||||||
|
"confbox": "^0.2.4",
|
||||||
"express": "^5.2.1",
|
"express": "^5.2.1",
|
||||||
"fs": "^0.0.1-security",
|
"fs": "^0.0.1-security",
|
||||||
"http-proxy-middleware": "^3.0.5",
|
"http-proxy-middleware": "^3.0.5",
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ import { promisify } from "util";
|
|||||||
import fs from "fs/promises";
|
import fs from "fs/promises";
|
||||||
import path from "path";
|
import path from "path";
|
||||||
import os from "os";
|
import os from "os";
|
||||||
|
import { parseTOML, stringifyTOML } from "confbox";
|
||||||
|
|
||||||
const execAsync = promisify(exec);
|
const execAsync = promisify(exec);
|
||||||
|
|
||||||
@@ -13,62 +14,31 @@ const getCodexDir = () => path.join(os.homedir(), ".codex");
|
|||||||
const getCodexConfigPath = () => path.join(getCodexDir(), "config.toml");
|
const getCodexConfigPath = () => path.join(getCodexDir(), "config.toml");
|
||||||
const getCodexAuthPath = () => path.join(getCodexDir(), "auth.json");
|
const getCodexAuthPath = () => path.join(getCodexDir(), "auth.json");
|
||||||
|
|
||||||
// Parse TOML config to object (simple parser for codex config)
|
// Flatten confbox-parsed TOML into a writable object, preserving nested tables
|
||||||
const parseToml = (content) => {
|
const parsedToWritable = (obj) => obj ?? {};
|
||||||
const result = { _root: {}, _sections: {} };
|
|
||||||
let currentSection = "_root";
|
// Set a nested key from a flat dotted path, creating intermediate objects as needed
|
||||||
|
const setNestedSection = (obj, dottedKey, value) => {
|
||||||
content.split("\n").forEach((line) => {
|
const keys = dottedKey.split(".");
|
||||||
const trimmed = line.trim();
|
let cur = obj;
|
||||||
if (!trimmed || trimmed.startsWith("#")) return;
|
for (let i = 0; i < keys.length - 1; i++) {
|
||||||
|
if (cur[keys[i]] == null || typeof cur[keys[i]] !== "object") {
|
||||||
// Section header like [model_providers.9router]
|
cur[keys[i]] = {};
|
||||||
const sectionMatch = trimmed.match(/^\[(.+)\]$/);
|
|
||||||
if (sectionMatch) {
|
|
||||||
currentSection = sectionMatch[1];
|
|
||||||
result._sections[currentSection] = {};
|
|
||||||
return;
|
|
||||||
}
|
}
|
||||||
|
cur = cur[keys[i]];
|
||||||
// Key = value
|
}
|
||||||
const kvMatch = trimmed.match(/^([^=]+)\s*=\s*(.+)$/);
|
cur[keys[keys.length - 1]] = value;
|
||||||
if (kvMatch) {
|
|
||||||
const key = kvMatch[1].trim();
|
|
||||||
let value = kvMatch[2].trim();
|
|
||||||
// Remove quotes
|
|
||||||
if ((value.startsWith('"') && value.endsWith('"')) || (value.startsWith("'") && value.endsWith("'"))) {
|
|
||||||
value = value.slice(1, -1);
|
|
||||||
}
|
|
||||||
if (currentSection === "_root") {
|
|
||||||
result._root[key] = value;
|
|
||||||
} else {
|
|
||||||
result._sections[currentSection][key] = value;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
return result;
|
|
||||||
};
|
};
|
||||||
|
|
||||||
// Convert parsed object back to TOML string
|
// Delete a nested key from a flat dotted path
|
||||||
const toToml = (parsed) => {
|
const deleteNestedSection = (obj, dottedKey) => {
|
||||||
let lines = [];
|
const keys = dottedKey.split(".");
|
||||||
|
let cur = obj;
|
||||||
// Root level keys
|
for (let i = 0; i < keys.length - 1; i++) {
|
||||||
Object.entries(parsed._root).forEach(([key, value]) => {
|
cur = cur?.[keys[i]];
|
||||||
lines.push(`${key} = "${value}"`);
|
if (cur == null) return;
|
||||||
});
|
}
|
||||||
|
delete cur[keys[keys.length - 1]];
|
||||||
// Sections
|
|
||||||
Object.entries(parsed._sections).forEach(([section, values]) => {
|
|
||||||
lines.push("");
|
|
||||||
lines.push(`[${section}]`);
|
|
||||||
Object.entries(values).forEach(([key, value]) => {
|
|
||||||
lines.push(`${key} = "${value}"`);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
return lines.join("\n") + "\n";
|
|
||||||
};
|
};
|
||||||
|
|
||||||
// Check if codex CLI is installed
|
// Check if codex CLI is installed
|
||||||
@@ -144,27 +114,27 @@ export async function POST(request) {
|
|||||||
await fs.mkdir(codexDir, { recursive: true });
|
await fs.mkdir(codexDir, { recursive: true });
|
||||||
|
|
||||||
// Read and parse existing config
|
// Read and parse existing config
|
||||||
let parsed = { _root: {}, _sections: {} };
|
let parsed = {};
|
||||||
try {
|
try {
|
||||||
const existingConfig = await fs.readFile(configPath, "utf-8");
|
const existingConfig = await fs.readFile(configPath, "utf-8");
|
||||||
parsed = parseToml(existingConfig);
|
parsed = parsedToWritable(parseTOML(existingConfig));
|
||||||
} catch { /* No existing config */ }
|
} catch { /* No existing config */ }
|
||||||
|
|
||||||
// Update only 9Router related fields (api_key goes to auth.json, not config.toml)
|
// Update only 9Router related fields (api_key goes to auth.json, not config.toml)
|
||||||
parsed._root.model = model;
|
parsed.model = model;
|
||||||
parsed._root.model_provider = "9router";
|
parsed.model_provider = "9router";
|
||||||
|
|
||||||
// Update or create 9router provider section (no api_key - Codex reads from auth.json)
|
// Update or create 9router provider section (no api_key - Codex reads from auth.json)
|
||||||
// Ensure /v1 suffix is added only once
|
// Ensure /v1 suffix is added only once
|
||||||
const normalizedBaseUrl = baseUrl.endsWith("/v1") ? baseUrl : `${baseUrl}/v1`;
|
const normalizedBaseUrl = baseUrl.endsWith("/v1") ? baseUrl : `${baseUrl}/v1`;
|
||||||
parsed._sections["model_providers.9router"] = {
|
setNestedSection(parsed, "model_providers.9router", {
|
||||||
name: "9Router",
|
name: "9Router",
|
||||||
base_url: normalizedBaseUrl,
|
base_url: normalizedBaseUrl,
|
||||||
wire_api: "responses",
|
wire_api: "responses",
|
||||||
};
|
});
|
||||||
|
|
||||||
// Write merged config
|
// Write merged config
|
||||||
const configContent = toToml(parsed);
|
const configContent = stringifyTOML(parsed);
|
||||||
await fs.writeFile(configPath, configContent);
|
await fs.writeFile(configPath, configContent);
|
||||||
|
|
||||||
// Update auth.json with OPENAI_API_KEY (Codex reads this first)
|
// Update auth.json with OPENAI_API_KEY (Codex reads this first)
|
||||||
@@ -195,10 +165,10 @@ export async function DELETE() {
|
|||||||
const configPath = getCodexConfigPath();
|
const configPath = getCodexConfigPath();
|
||||||
|
|
||||||
// Read and parse existing config
|
// Read and parse existing config
|
||||||
let parsed = { _root: {}, _sections: {} };
|
let parsed = {};
|
||||||
try {
|
try {
|
||||||
const existingConfig = await fs.readFile(configPath, "utf-8");
|
const existingConfig = await fs.readFile(configPath, "utf-8");
|
||||||
parsed = parseToml(existingConfig);
|
parsed = parsedToWritable(parseTOML(existingConfig));
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
if (error.code === "ENOENT") {
|
if (error.code === "ENOENT") {
|
||||||
return NextResponse.json({
|
return NextResponse.json({
|
||||||
@@ -210,16 +180,16 @@ export async function DELETE() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Remove 9Router related root fields only if they point to 9router
|
// Remove 9Router related root fields only if they point to 9router
|
||||||
if (parsed._root.model_provider === "9router") {
|
if (parsed.model_provider === "9router") {
|
||||||
delete parsed._root.model;
|
delete parsed.model;
|
||||||
delete parsed._root.model_provider;
|
delete parsed.model_provider;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Remove 9router provider section
|
// Remove 9router provider section
|
||||||
delete parsed._sections["model_providers.9router"];
|
deleteNestedSection(parsed, "model_providers.9router");
|
||||||
|
|
||||||
// Write updated config
|
// Write updated config
|
||||||
const configContent = toToml(parsed);
|
const configContent = stringifyTOML(parsed);
|
||||||
await fs.writeFile(configPath, configContent);
|
await fs.writeFile(configPath, configContent);
|
||||||
|
|
||||||
// Remove OPENAI_API_KEY from auth.json
|
// Remove OPENAI_API_KEY from auth.json
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ import { getUsageForProvider } from "open-sse/services/usage.js";
|
|||||||
import { getExecutor } from "open-sse/executors/index.js";
|
import { getExecutor } from "open-sse/executors/index.js";
|
||||||
/**
|
/**
|
||||||
* Refresh credentials using executor and update database
|
* Refresh credentials using executor and update database
|
||||||
* @returns {{ connection, refreshed: boolean }}
|
* @returns Promise<{ connection, refreshed: boolean }>
|
||||||
*/
|
*/
|
||||||
async function refreshAndUpdateCredentials(connection) {
|
async function refreshAndUpdateCredentials(connection) {
|
||||||
const executor = getExecutor(connection.provider);
|
const executor = getExecutor(connection.provider);
|
||||||
|
|||||||
Reference in New Issue
Block a user