diff --git a/backend/package.json b/backend/package.json index 31c86b26..7931806d 100644 --- a/backend/package.json +++ b/backend/package.json @@ -17,6 +17,7 @@ "@opencode-manager/shared": "workspace:*", "dotenv": "^17.2.3", "hono": "^4.10.1", + "strip-json-comments": "^3.1.1", "zod": "^4.1.12" }, "devDependencies": { diff --git a/backend/src/routes/settings.ts b/backend/src/routes/settings.ts index e4ddefa6..8f36069c 100644 --- a/backend/src/routes/settings.ts +++ b/backend/src/routes/settings.ts @@ -18,12 +18,12 @@ const UpdateSettingsSchema = z.object({ const CreateOpenCodeConfigSchema = z.object({ name: z.string().min(1).max(255), - content: OpenCodeConfigSchema, + content: z.union([OpenCodeConfigSchema, z.string()]), isDefault: z.boolean().optional(), }) const UpdateOpenCodeConfigSchema = z.object({ - content: OpenCodeConfigSchema, + content: z.union([OpenCodeConfigSchema, z.string()]), isDefault: z.boolean().optional(), }) diff --git a/backend/src/services/files.ts b/backend/src/services/files.ts index bbc062a1..b0f265af 100644 --- a/backend/src/services/files.ts +++ b/backend/src/services/files.ts @@ -248,6 +248,7 @@ function getMimeType(filePath: string, _content: Uint8Array): string { '.jsx': 'text/javascript', '.tsx': 'text/typescript', '.json': 'application/json', + '.jsonc': 'application/json', '.xml': 'application/xml', '.png': 'image/png', '.jpg': 'image/jpeg', diff --git a/backend/src/services/settings.ts b/backend/src/services/settings.ts index 0bffbb62..108c6ab8 100644 --- a/backend/src/services/settings.ts +++ b/backend/src/services/settings.ts @@ -1,20 +1,32 @@ import { Database } from 'bun:sqlite' import { logger } from '../utils/logger' +import stripJsonComments from 'strip-json-comments' import type { UserPreferences, SettingsResponse, OpenCodeConfig, CreateOpenCodeConfigRequest, - UpdateOpenCodeConfigRequest, - OpenCodeConfigResponse + UpdateOpenCodeConfigRequest } from '../types/settings' import { UserPreferencesSchema, OpenCodeConfigSchema, - OpenCodeConfigMetadataSchema, DEFAULT_USER_PREFERENCES, } from '../types/settings' +interface OpenCodeConfigWithRaw extends OpenCodeConfig { + rawContent: string +} + +interface OpenCodeConfigResponseWithRaw { + configs: OpenCodeConfigWithRaw[] + defaultConfig: OpenCodeConfigWithRaw | null +} + +function parseJsonc(content: string): unknown { + return JSON.parse(stripJsonComments(content)) +} + export class SettingsService { constructor(private db: Database) {} @@ -31,7 +43,7 @@ export class SettingsService { } try { - const parsed = JSON.parse(row.preferences) + const parsed = parseJsonc(row.preferences) as Record const validated = UserPreferencesSchema.parse({ ...DEFAULT_USER_PREFERENCES, ...parsed, @@ -92,7 +104,7 @@ export class SettingsService { } } - getOpenCodeConfigs(userId: string = 'default'): OpenCodeConfigResponse { + getOpenCodeConfigs(userId: string = 'default'): OpenCodeConfigResponseWithRaw { const rows = this.db .query('SELECT * FROM opencode_configs WHERE user_id = ? ORDER BY created_at DESC') .all(userId) as Array<{ @@ -105,18 +117,20 @@ export class SettingsService { updated_at: number }> - const configs: OpenCodeConfig[] = [] - let defaultConfig: OpenCodeConfig | null = null + const configs: OpenCodeConfigWithRaw[] = [] + let defaultConfig: OpenCodeConfigWithRaw | null = null for (const row of rows) { try { - const content = JSON.parse(row.config_content) + const rawContent = row.config_content + const content = parseJsonc(rawContent) const validated = OpenCodeConfigSchema.parse(content) - const config: OpenCodeConfig = { + const config: OpenCodeConfigWithRaw = { id: row.id, name: row.config_name, content: validated, + rawContent: rawContent, isDefault: Boolean(row.is_default), createdAt: row.created_at, updatedAt: row.updated_at, @@ -141,8 +155,16 @@ export class SettingsService { createOpenCodeConfig( request: CreateOpenCodeConfigRequest, userId: string = 'default' - ): OpenCodeConfig { - const contentValidated = OpenCodeConfigSchema.parse(request.content) + ): OpenCodeConfigWithRaw { + const rawContent = typeof request.content === 'string' + ? request.content + : JSON.stringify(request.content, null, 2) + + const parsedContent = typeof request.content === 'string' + ? parseJsonc(request.content) + : request.content + + const contentValidated = OpenCodeConfigSchema.parse(parsedContent) const now = Date.now() const existingCount = this.db @@ -165,16 +187,17 @@ export class SettingsService { .run( userId, request.name, - JSON.stringify(contentValidated), + rawContent, shouldBeDefault, now, now ) - const config: OpenCodeConfig = { + const config: OpenCodeConfigWithRaw = { id: result.lastInsertRowid as number, name: request.name, content: contentValidated, + rawContent: rawContent, isDefault: shouldBeDefault, createdAt: now, updatedAt: now, @@ -188,7 +211,7 @@ export class SettingsService { configName: string, request: UpdateOpenCodeConfigRequest, userId: string = 'default' - ): OpenCodeConfig | null { + ): OpenCodeConfigWithRaw | null { const existing = this.db .query('SELECT * FROM opencode_configs WHERE user_id = ? AND config_name = ?') .get(userId, configName) as { @@ -202,7 +225,15 @@ export class SettingsService { return null } - const contentValidated = OpenCodeConfigSchema.parse(request.content) + const rawContent = typeof request.content === 'string' + ? request.content + : JSON.stringify(request.content, null, 2) + + const parsedContent = typeof request.content === 'string' + ? parseJsonc(request.content) + : request.content + + const contentValidated = OpenCodeConfigSchema.parse(parsedContent) const now = Date.now() if (request.isDefault) { @@ -218,17 +249,18 @@ export class SettingsService { WHERE user_id = ? AND config_name = ?` ) .run( - JSON.stringify(contentValidated), + rawContent, request.isDefault !== undefined ? request.isDefault : existing.is_default, now, userId, configName ) - const config: OpenCodeConfig = { + const config: OpenCodeConfigWithRaw = { id: existing.id, name: configName, content: contentValidated, + rawContent: rawContent, isDefault: request.isDefault !== undefined ? request.isDefault : existing.is_default, createdAt: existing.created_at, updatedAt: now, @@ -252,7 +284,7 @@ export class SettingsService { return deleted } - setDefaultOpenCodeConfig(configName: string, userId: string = 'default'): OpenCodeConfig | null { + setDefaultOpenCodeConfig(configName: string, userId: string = 'default'): OpenCodeConfigWithRaw | null { const existing = this.db .query('SELECT * FROM opencode_configs WHERE user_id = ? AND config_name = ?') .get(userId, configName) as { @@ -279,13 +311,15 @@ export class SettingsService { .run(now, userId, configName) try { - const content = JSON.parse(existing.config_content) + const rawContent = existing.config_content + const content = parseJsonc(rawContent) const validated = OpenCodeConfigSchema.parse(content) - const config: OpenCodeConfig = { + const config: OpenCodeConfigWithRaw = { id: existing.id, name: configName, content: validated, + rawContent: rawContent, isDefault: true, createdAt: existing.created_at, updatedAt: now, @@ -299,7 +333,7 @@ export class SettingsService { } } - getDefaultOpenCodeConfig(userId: string = 'default'): OpenCodeConfig | null { + getDefaultOpenCodeConfig(userId: string = 'default'): OpenCodeConfigWithRaw | null { const row = this.db .query('SELECT * FROM opencode_configs WHERE user_id = ? AND is_default = TRUE') .get(userId) as { @@ -315,13 +349,15 @@ export class SettingsService { } try { - const content = JSON.parse(row.config_content) + const rawContent = row.config_content + const content = parseJsonc(rawContent) const validated = OpenCodeConfigSchema.parse(content) return { id: row.id, name: row.config_name, content: validated, + rawContent: rawContent, isDefault: true, createdAt: row.created_at, updatedAt: row.updated_at, @@ -332,7 +368,7 @@ export class SettingsService { } } - getOpenCodeConfigByName(configName: string, userId: string = 'default'): OpenCodeConfig | null { + getOpenCodeConfigByName(configName: string, userId: string = 'default'): OpenCodeConfigWithRaw | null { const row = this.db .query('SELECT * FROM opencode_configs WHERE user_id = ? AND config_name = ?') .get(userId, configName) as { @@ -349,13 +385,15 @@ export class SettingsService { } try { - const content = JSON.parse(row.config_content) + const rawContent = row.config_content + const content = parseJsonc(rawContent) const validated = OpenCodeConfigSchema.parse(content) return { id: row.id, name: row.config_name, content: validated, + rawContent: rawContent, isDefault: Boolean(row.is_default), createdAt: row.created_at, updatedAt: row.updated_at, @@ -367,19 +405,16 @@ export class SettingsService { } getOpenCodeConfigContent(configName: string, userId: string = 'default'): string | null { - const config = this.getOpenCodeConfigByName(configName, userId) + const row = this.db + .query('SELECT config_content FROM opencode_configs WHERE user_id = ? AND config_name = ?') + .get(userId, configName) as { config_content: string } | undefined - if (!config) { + if (!row) { logger.error(`Config '${configName}' not found for user ${userId}`) return null } - try { - return JSON.stringify(config.content, null, 2) - } catch (error) { - logger.error(`Failed to stringify config '${configName}':`, error) - return null - } + return row.config_content } ensureSingleConfigIsDefault(userId: string = 'default'): void { diff --git a/frontend/package-lock.json b/frontend/package-lock.json index d5d405f4..032f1f43 100644 --- a/frontend/package-lock.json +++ b/frontend/package-lock.json @@ -36,6 +36,7 @@ "rehype-raw": "^7.0.0", "remark-gfm": "^4.0.1", "sonner": "^2.0.7", + "strip-json-comments": "^5.0.3", "tailwind-merge": "^3.3.1", "zod": "^4.1.12", "zustand": "^5.0.8" @@ -90,6 +91,7 @@ "integrity": "sha512-e7jT4DxYvIDLk1ZHmU/m/mB19rex9sv0c2ftBtjSBv+kVM/902eh0fINUzD7UwLLNR+jU585GxUJ8/EBfAM5fw==", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "@babel/code-frame": "^7.27.1", "@babel/generator": "^7.28.5", @@ -877,6 +879,19 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/@eslint/eslintrc/node_modules/strip-json-comments": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-3.1.1.tgz", + "integrity": "sha512-6fPc+R4ihwqP6N/aIv2f1gMH8lOVtWQHoqC4yK6oSDVVocumAsfCqjkXnqiYMhmMwS/mEHLp7Vehlt3ql6lEig==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/@eslint/js": { "version": "9.39.1", "resolved": "https://registry.npmjs.org/@eslint/js/-/js-9.39.1.tgz", @@ -2762,6 +2777,7 @@ "integrity": "sha512-GNWcUTRBgIRJD5zj+Tq0fKOJ5XZajIiBroOF0yvj2bSU1WvNdYS/dn9UxwsujGW4JX06dnHyjV2y9rRaybH0iQ==", "devOptional": true, "license": "MIT", + "peer": true, "dependencies": { "undici-types": "~7.16.0" } @@ -2771,6 +2787,7 @@ "resolved": "https://registry.npmjs.org/@types/react/-/react-19.2.7.tgz", "integrity": "sha512-MWtvHrGZLFttgeEj28VXHxpmwYbor/ATPYbBfSFZEIRK0ecCFLl2Qo55z52Hss+UV9CRN7trSeq1zbgx7YDWWg==", "license": "MIT", + "peer": true, "dependencies": { "csstype": "^3.2.2" } @@ -2781,6 +2798,7 @@ "integrity": "sha512-jp2L/eY6fn+KgVVQAOqYItbF0VY/YApe5Mz2F0aykSO8gx31bYCZyvSeYxCHKvzHG5eZjc+zyaS5BrBWya2+kQ==", "devOptional": true, "license": "MIT", + "peer": true, "peerDependencies": { "@types/react": "^19.2.0" } @@ -2790,8 +2808,7 @@ "resolved": "https://registry.npmjs.org/@types/trusted-types/-/trusted-types-2.0.7.tgz", "integrity": "sha512-ScaPdn1dQczgbl0QFTeTOmVHFULt394XJgOQNoyVhZ6r2vLnMLJfBPd53SB52T/3G36VI1/g2MZaX0cwDuXsfw==", "license": "MIT", - "optional": true, - "peer": true + "optional": true }, "node_modules/@types/unist": { "version": "3.0.3", @@ -2845,6 +2862,7 @@ "integrity": "sha512-jCzKdm/QK0Kg4V4IK/oMlRZlY+QOcdjv89U2NgKHZk1CYTj82/RVSx1mV/0gqCVMJ/DA+Zf/S4NBWNF8GQ+eqQ==", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "@typescript-eslint/scope-manager": "8.48.0", "@typescript-eslint/types": "8.48.0", @@ -3102,6 +3120,7 @@ "integrity": "sha512-NZyJarBfL7nWwIq+FDL6Zp/yHEhePMNnnJ0y3qfieCrmNvYct8uvtiV41UvlSe6apAfk0fY1FbWx+NwfmpvtTg==", "dev": true, "license": "MIT", + "peer": true, "bin": { "acorn": "bin/acorn" }, @@ -3304,6 +3323,7 @@ } ], "license": "MIT", + "peer": true, "dependencies": { "baseline-browser-mapping": "^2.8.25", "caniuse-lite": "^1.0.30001754", @@ -3677,7 +3697,6 @@ "resolved": "https://registry.npmjs.org/dompurify/-/dompurify-3.2.7.tgz", "integrity": "sha512-WhL/YuveyGXJaerVlMYGWhvQswa7myDG17P7Vu65EWC05o8vfeNbvNf4d/BOvH99+ZW+LlQsc1GDKMa1vNK6dw==", "license": "(MPL-2.0 OR Apache-2.0)", - "peer": true, "optionalDependencies": { "@types/trusted-types": "^2.0.7" } @@ -3843,6 +3862,7 @@ "integrity": "sha512-BhHmn2yNOFA9H9JmmIVKJmd288g9hrVRDkdoIgRCRuSySRUHH7r/DI6aAXW9T1WwUuY3DFgrcaqB+deURBLR5g==", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "@eslint-community/eslint-utils": "^4.8.0", "@eslint-community/regexpp": "^4.12.1", @@ -5173,7 +5193,6 @@ "resolved": "https://registry.npmjs.org/marked/-/marked-14.0.0.tgz", "integrity": "sha512-uIj4+faQ+MgHgwUW1l2PsPglZLOLOT1uErt06dAPtx2kjteLAkbsd/0FiYg/MGS+i7ZKLb7w2WClxHkzOOuryQ==", "license": "MIT", - "peer": true, "bin": { "marked": "bin/marked.js" }, @@ -6311,6 +6330,7 @@ "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.3.tgz", "integrity": "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q==", "license": "MIT", + "peer": true, "engines": { "node": ">=12" }, @@ -6347,6 +6367,7 @@ } ], "license": "MIT", + "peer": true, "dependencies": { "nanoid": "^3.3.11", "picocolors": "^1.1.1", @@ -6404,6 +6425,7 @@ "resolved": "https://registry.npmjs.org/react/-/react-19.2.0.tgz", "integrity": "sha512-tmbWg6W31tQLeB5cdIBOicJDJRR2KzXsV7uSK9iNfLWQ5bIZfxuPEHp7M8wiHyHnn0DD1i7w3Zmin0FtkrwoCQ==", "license": "MIT", + "peer": true, "engines": { "node": ">=0.10.0" } @@ -6413,6 +6435,7 @@ "resolved": "https://registry.npmjs.org/react-dom/-/react-dom-19.2.0.tgz", "integrity": "sha512-UlbRu4cAiGaIewkPyiRGJk0imDN2T3JjieT6spoL2UeSf5od4n5LB/mQ4ejmxhCFT1tYe8IvaFulzynWovsEFQ==", "license": "MIT", + "peer": true, "dependencies": { "scheduler": "^0.27.0" }, @@ -6425,6 +6448,7 @@ "resolved": "https://registry.npmjs.org/react-hook-form/-/react-hook-form-7.67.0.tgz", "integrity": "sha512-E55EOwKJHHIT/I6J9DmQbCWToAYSw9nN5R57MZw9rMtjh+YQreMDxRLfdjfxQbiJ3/qbg3Z02wGzBX4M+5fMtQ==", "license": "MIT", + "peer": true, "engines": { "node": ">=18.0.0" }, @@ -6834,13 +6858,12 @@ } }, "node_modules/strip-json-comments": { - "version": "3.1.1", - "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-3.1.1.tgz", - "integrity": "sha512-6fPc+R4ihwqP6N/aIv2f1gMH8lOVtWQHoqC4yK6oSDVVocumAsfCqjkXnqiYMhmMwS/mEHLp7Vehlt3ql6lEig==", - "dev": true, + "version": "5.0.3", + "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-5.0.3.tgz", + "integrity": "sha512-1tB5mhVo7U+ETBKNf92xT4hrQa3pm0MZ0PQvuDnWgAAGHDsfp4lPSpiS6psrSiet87wyGPh9ft6wmhOMQ0hDiw==", "license": "MIT", "engines": { - "node": ">=8" + "node": ">=14.16" }, "funding": { "url": "https://github.com/sponsors/sindresorhus" @@ -6993,6 +7016,7 @@ "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==", "dev": true, "license": "Apache-2.0", + "peer": true, "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" @@ -7264,6 +7288,7 @@ "resolved": "https://registry.npmjs.org/vite/-/vite-7.2.4.tgz", "integrity": "sha512-NL8jTlbo0Tn4dUEXEsUg8KeyG/Lkmc4Fnzb8JXN/Ykm9G4HNImjtABMJgkQoVjOBN/j2WAwDTRytdqJbZsah7w==", "license": "MIT", + "peer": true, "dependencies": { "esbuild": "^0.25.0", "fdir": "^6.5.0", diff --git a/frontend/package.json b/frontend/package.json index 79b67e6f..ece9f10b 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -39,6 +39,7 @@ "rehype-raw": "^7.0.0", "remark-gfm": "^4.0.1", "sonner": "^2.0.7", + "strip-json-comments": "^5.0.3", "tailwind-merge": "^3.3.1", "zod": "^4.1.12", "zustand": "^5.0.8" diff --git a/frontend/src/api/types/settings.ts b/frontend/src/api/types/settings.ts index afb3ba8b..94e7ce24 100644 --- a/frontend/src/api/types/settings.ts +++ b/frontend/src/api/types/settings.ts @@ -57,6 +57,7 @@ export interface OpenCodeConfig { id: number name: string content: Record + rawContent?: string isDefault: boolean createdAt: number updatedAt: number @@ -64,12 +65,12 @@ export interface OpenCodeConfig { export interface CreateOpenCodeConfigRequest { name: string - content: Record + content: Record | string isDefault?: boolean } export interface UpdateOpenCodeConfigRequest { - content: Record + content: Record | string isDefault?: boolean } diff --git a/frontend/src/components/settings/CreateConfigDialog.tsx b/frontend/src/components/settings/CreateConfigDialog.tsx index bfb53f35..29f5c9ca 100644 --- a/frontend/src/components/settings/CreateConfigDialog.tsx +++ b/frontend/src/components/settings/CreateConfigDialog.tsx @@ -6,6 +6,7 @@ import { Input } from '@/components/ui/input' import { Label } from '@/components/ui/label' import { Textarea } from '@/components/ui/textarea' import { Switch } from '@/components/ui/switch' +import stripJsonComments from 'strip-json-comments' interface CreateConfigDialogProps { isOpen: boolean @@ -62,11 +63,11 @@ export function CreateConfigDialog({ isOpen, onOpenChange, onCreate, isUpdating reader.onload = (e) => { const fileContent = e.target?.result as string try { - JSON.parse(fileContent) + JSON.parse(stripJsonComments(fileContent)) setContent(fileContent) setName(file.name.replace('.json', '').replace('.jsonc', '')) } catch { - window.alert('Invalid JSON file') + window.alert('Invalid JSON/JSONC file') } } reader.readAsText(file) diff --git a/frontend/src/components/settings/OpenCodeConfigEditor.tsx b/frontend/src/components/settings/OpenCodeConfigEditor.tsx index e675db42..e6a8c233 100644 --- a/frontend/src/components/settings/OpenCodeConfigEditor.tsx +++ b/frontend/src/components/settings/OpenCodeConfigEditor.tsx @@ -4,12 +4,13 @@ import { Label } from '@/components/ui/label' import { Textarea } from '@/components/ui/textarea' import { Loader2 } from 'lucide-react' import type { OpenCodeConfig } from '@/api/types/settings' +import stripJsonComments from 'strip-json-comments' interface OpenCodeConfigEditorProps { config: OpenCodeConfig | null isOpen: boolean onClose: () => void - onUpdate: (content: Record) => Promise + onUpdate: (content: string) => Promise isUpdating: boolean } @@ -27,7 +28,7 @@ export function OpenCodeConfigEditor({ useEffect(() => { if (config && isOpen) { - setEditConfigContent(JSON.stringify(config.content, null, 2)) + setEditConfigContent(config.rawContent || JSON.stringify(config.content, null, 2)) setEditError('') setEditErrorLine(null) } @@ -43,7 +44,7 @@ export function OpenCodeConfigEditor({ if (!config) return try { - const parsedContent = JSON.parse(editConfigContent) + const parsedContent = JSON.parse(stripJsonComments(editConfigContent)) const forbiddenFields = ['id', 'createdAt', 'updatedAt'] const foundForbidden = forbiddenFields.filter(field => field in parsedContent) @@ -51,14 +52,14 @@ export function OpenCodeConfigEditor({ throw new Error(`Invalid fields found: ${foundForbidden.join(', ')}. These fields are managed automatically.`) } - await onUpdate(parsedContent) + await onUpdate(editConfigContent) onClose() } catch (error) { if (error instanceof SyntaxError) { const match = error.message.match(/line (\d+)/i) const line = match ? parseInt(match[1]) : null setEditErrorLine(line) - setEditError('Invalid JSON format') + setEditError('Invalid JSON/JSONC format') } else { setEditError(error instanceof Error ? error.message : 'Failed to update config') } @@ -93,7 +94,7 @@ export function OpenCodeConfigEditor({