2025-12-07 19:32:53 +02:00
|
|
|
import type { SettingsAPI, SettingsLoadResult, SettingsPayload } from '@openchamber/ui/lib/api/types';
|
2026-06-02 00:43:05 +03:00
|
|
|
import { runtimeFetch } from '@openchamber/ui/lib/runtime-fetch';
|
2025-12-07 19:32:53 +02:00
|
|
|
|
|
|
|
|
const SETTINGS_ENDPOINT = '/api/config/settings';
|
|
|
|
|
const RELOAD_ENDPOINT = '/api/config/reload';
|
|
|
|
|
|
|
|
|
|
const sanitizePayload = (data: unknown): SettingsPayload => {
|
2026-07-21 20:52:20 +03:00
|
|
|
if (!data || typeof data !== 'object' || Array.isArray(data)) throw new Error('Invalid settings response');
|
2025-12-07 19:32:53 +02:00
|
|
|
return data as SettingsPayload;
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
export const createWebSettingsAPI = (): SettingsAPI => ({
|
|
|
|
|
async load(): Promise<SettingsLoadResult> {
|
2026-06-02 00:43:05 +03:00
|
|
|
const response = await runtimeFetch(SETTINGS_ENDPOINT, {
|
2025-12-07 19:32:53 +02:00
|
|
|
method: 'GET',
|
|
|
|
|
headers: { Accept: 'application/json' },
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
if (!response.ok) {
|
|
|
|
|
throw new Error(`Failed to load settings: ${response.statusText}`);
|
|
|
|
|
}
|
|
|
|
|
|
2026-07-21 20:52:20 +03:00
|
|
|
const payload = sanitizePayload(await response.json());
|
2025-12-07 19:32:53 +02:00
|
|
|
return {
|
|
|
|
|
settings: payload,
|
|
|
|
|
source: 'web',
|
|
|
|
|
};
|
|
|
|
|
},
|
|
|
|
|
|
|
|
|
|
async save(changes: Partial<SettingsPayload>): Promise<SettingsPayload> {
|
2026-06-02 00:43:05 +03:00
|
|
|
const response = await runtimeFetch(SETTINGS_ENDPOINT, {
|
2025-12-07 19:32:53 +02:00
|
|
|
method: 'PUT',
|
|
|
|
|
headers: {
|
|
|
|
|
'Content-Type': 'application/json',
|
|
|
|
|
Accept: 'application/json',
|
|
|
|
|
},
|
|
|
|
|
body: JSON.stringify(changes),
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
if (!response.ok) {
|
|
|
|
|
const error = await response.json().catch(() => ({ error: response.statusText }));
|
|
|
|
|
throw new Error(error.error || 'Failed to save settings');
|
|
|
|
|
}
|
|
|
|
|
|
2026-07-21 20:52:20 +03:00
|
|
|
const payload = sanitizePayload(await response.json());
|
2025-12-07 19:32:53 +02:00
|
|
|
return payload;
|
|
|
|
|
},
|
|
|
|
|
|
|
|
|
|
async restartOpenCode(): Promise<{ restarted: boolean }> {
|
2026-06-02 00:43:05 +03:00
|
|
|
const response = await runtimeFetch(RELOAD_ENDPOINT, { method: 'POST' });
|
2025-12-07 19:32:53 +02:00
|
|
|
if (!response.ok) {
|
|
|
|
|
const error = await response.json().catch(() => ({ error: response.statusText }));
|
|
|
|
|
throw new Error(error.error || 'Failed to restart OpenCode');
|
|
|
|
|
}
|
|
|
|
|
return { restarted: true };
|
|
|
|
|
},
|
|
|
|
|
});
|