From e1a4a70d3ddade3883ac2af92cd68ee4701b76ab Mon Sep 17 00:00:00 2001 From: Chris Scott <99081550+chriswritescode-dev@users.noreply.github.com> Date: Sat, 7 Mar 2026 10:42:18 -0500 Subject: [PATCH] Replace strip-json-comments with jsonc-parser for better error reporting --- backend/package.json | 2 +- backend/src/index.ts | 6 +-- backend/src/services/settings.ts | 5 +-- frontend/package.json | 2 +- frontend/src/api/fetchWrapper.ts | 23 +++++++++- .../settings/OpenCodeConfigEditor.tsx | 45 +++++++++++++------ frontend/src/index.css | 21 +++++++++ frontend/src/lib/jsonc.ts | 10 +---- shared/package.json | 3 +- shared/src/index.ts | 1 + shared/src/schemas/settings.ts | 2 +- shared/src/utils/index.ts | 1 + shared/src/utils/jsonc.ts | 45 +++++++++++++++++++ 13 files changed, 132 insertions(+), 34 deletions(-) create mode 100644 shared/src/utils/index.ts create mode 100644 shared/src/utils/jsonc.ts diff --git a/backend/package.json b/backend/package.json index 0c2d7dcf..a2205544 100644 --- a/backend/package.json +++ b/backend/package.json @@ -23,7 +23,7 @@ "dotenv": "^17.2.3", "eventsource": "^4.1.0", "hono": "^4.11.7", - "strip-json-comments": "^3.1.1", + "jsonc-parser": "^3.3.1", "web-push": "^3.6.7", "zod": "^4.1.12" }, diff --git a/backend/src/index.ts b/backend/src/index.ts index 202c68d6..4fff13ac 100644 --- a/backend/src/index.ts +++ b/backend/src/index.ts @@ -54,7 +54,7 @@ import { ENV } from '@opencode-manager/shared/config/env' import { OpenCodeConfigSchema } from '@opencode-manager/shared/schemas' -import stripJsonComments from 'strip-json-comments' +import { parse as parseJsonc } from 'jsonc-parser' const { PORT, HOST } = ENV.SERVER const DB_PATH = getDatabasePath() @@ -90,7 +90,7 @@ async function ensureDefaultConfigExists(): Promise { logger.info(`Found workspace config at ${workspaceConfigPath}, syncing to database...`) try { const rawContent = await readFileContent(workspaceConfigPath) - const parsed = JSON.parse(stripJsonComments(rawContent)) + const parsed = parseJsonc(rawContent) const validation = OpenCodeConfigSchema.safeParse(parsed) if (!validation.success) { @@ -123,7 +123,7 @@ async function ensureDefaultConfigExists(): Promise { logger.info(`Found home config at ${homeConfigPath}, importing...`) try { const rawContent = await readFileContent(homeConfigPath) - const parsed = JSON.parse(stripJsonComments(rawContent)) + const parsed = parseJsonc(rawContent) const validation = OpenCodeConfigSchema.safeParse(parsed) if (validation.success) { diff --git a/backend/src/services/settings.ts b/backend/src/services/settings.ts index c6ec1d01..54890997 100644 --- a/backend/src/services/settings.ts +++ b/backend/src/services/settings.ts @@ -2,7 +2,7 @@ import { Database } from 'bun:sqlite' import { unlinkSync, existsSync } from 'fs' import { getOpenCodeConfigFilePath } from '@opencode-manager/shared/config/env' import { logger } from '../utils/logger' -import stripJsonComments from 'strip-json-comments' +import { parseJsonc } from '@opencode-manager/shared/utils' import type { UserPreferences, SettingsResponse, @@ -25,9 +25,6 @@ interface OpenCodeConfigResponseWithRaw { defaultConfig: OpenCodeConfigWithRaw | null } -function parseJsonc(content: string): unknown { - return JSON.parse(stripJsonComments(content)) -} export class SettingsService { private static lastKnownGoodConfigContent: string | null = null diff --git a/frontend/package.json b/frontend/package.json index b8ba2f8e..9acb2891 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -36,6 +36,7 @@ "date-fns": "^4.1.0", "diff": "^8.0.2", "highlight.js": "^11.11.1", + "jsonc-parser": "^3.3.1", "lucide-react": "^0.546.0", "mermaid": "^11.12.2", "react": "^19.1.1", @@ -47,7 +48,6 @@ "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/fetchWrapper.ts b/frontend/src/api/fetchWrapper.ts index 607e487a..441e1ff7 100644 --- a/frontend/src/api/fetchWrapper.ts +++ b/frontend/src/api/fetchWrapper.ts @@ -8,13 +8,34 @@ interface FetchWrapperOptions extends RequestInit { params?: Record } +function formatDetails(details: unknown): string | undefined { + if (Array.isArray(details)) { + return details + .map((d) => { + if (typeof d !== 'object' || d === null) return null + const path = Array.isArray((d as Record).path) + ? ((d as Record).path as string[]) + : undefined + const message = typeof (d as Record).message === 'string' + ? (d as Record).message as string + : undefined + return path?.length ? `${path.join('.')}: ${message}` : message + }) + .filter(Boolean) + .join('; ') + } + if (typeof details === 'string') return details + return undefined +} + async function handleResponse(response: Response): Promise { const data: ApiErrorResponse = await response.json().catch(() => ({ error: 'An error occurred' })) + const detail = data.detail || formatDetails(data.details) throw new FetchError( data.error || 'Request failed', response.status, data.code, - data.detail + detail ) } diff --git a/frontend/src/components/settings/OpenCodeConfigEditor.tsx b/frontend/src/components/settings/OpenCodeConfigEditor.tsx index 662a1ee5..8c4305ee 100644 --- a/frontend/src/components/settings/OpenCodeConfigEditor.tsx +++ b/frontend/src/components/settings/OpenCodeConfigEditor.tsx @@ -5,6 +5,7 @@ import { Loader2 } from 'lucide-react' import { Dialog, DialogContent, DialogHeader, DialogFooter, DialogTitle } from '@/components/ui/dialog' import type { OpenCodeConfig } from '@/api/types/settings' import { parseJsonc } from '@/lib/jsonc' +import { FetchError } from '@/api/fetchWrapper' interface OpenCodeConfigEditorProps { config: OpenCodeConfig | null @@ -44,28 +45,46 @@ export function OpenCodeConfigEditor({ if (!config) return try { - const parsedContent = parseJsonc>(editConfigContent) - - const forbiddenFields = ['id', 'createdAt', 'updatedAt'] - const foundForbidden = forbiddenFields.filter(field => field in parsedContent) - if (foundForbidden.length > 0) { - throw new Error(`Invalid fields found: ${foundForbidden.join(', ')}. These fields are managed automatically.`) - } - + parseJsonc>(editConfigContent) 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 + const lineMatch = error.message.match(/line\s+(\d+)/i) + const line = lineMatch ? parseInt(lineMatch[1]) : null setEditErrorLine(line) - setEditError('Invalid JSON/JSONC format') + if (line && editTextareaRef.current) { + highlightErrorLine(editTextareaRef.current, line) + } + setEditError(`Invalid JSON/JSONC: ${error.message}`) + } else if (error instanceof FetchError) { + setEditError(error.detail || error.message) + } else if (error instanceof Error) { + setEditError(error.message) } else { - setEditError('Failed to save. Please check your changes and try again.') + setEditError('Failed to save configuration') } } } + const highlightErrorLine = (textarea: HTMLTextAreaElement, line: number) => { + const lines = textarea.value.split('\n') + if (line > lines.length) return + + let charIndex = 0 + for (let i = 0; i < line - 1; i++) { + charIndex += lines[i].length + 1 + } + + textarea.focus() + textarea.setSelectionRange(charIndex, charIndex + lines[line - 1].length) + + // Scroll to make the error line visible + const lineHeight = textarea.scrollHeight / lines.length + const targetPosition = lineHeight * (line - 1) + textarea.scrollTop = targetPosition - textarea.clientHeight / 2 + lineHeight / 2 + } + if (!config) return null return ( @@ -87,7 +106,7 @@ export function OpenCodeConfigEditor({ setEditError('') setEditErrorLine(null) }} - className="flex-1 font-mono text-[16px] sm:text-xs md:text-sm resize-none h-full rounded-none sm:rounded-md" + className={`flex-1 font-mono text-[16px] sm:text-xs md:text-sm resize-none h-full rounded-none sm:rounded-md ${editErrorLine ? 'error-highlight' : ''}`} /> {editError && (
diff --git a/frontend/src/index.css b/frontend/src/index.css index 4f19a6ae..7dc955c7 100644 --- a/frontend/src/index.css +++ b/frontend/src/index.css @@ -374,3 +374,24 @@ body { .animate-progress { animation: progress 2s ease-in-out infinite; } + +/* Error line highlighting - red-orange selection color */ +.error-highlight::selection { + background-color: #fecaca; + color: #991b1b; +} + +.dark .error-highlight::selection { + background-color: #7f1d1d; + color: #fecaca; +} + +.error-highlight::-moz-selection { + background-color: #fecaca; + color: #991b1b; +} + +.dark .error-highlight::-moz-selection { + background-color: #7f1d1d; + color: #fecaca; +} diff --git a/frontend/src/lib/jsonc.ts b/frontend/src/lib/jsonc.ts index f32dba67..02d48205 100644 --- a/frontend/src/lib/jsonc.ts +++ b/frontend/src/lib/jsonc.ts @@ -1,12 +1,4 @@ -import stripJsonComments from 'strip-json-comments' - -export function parseJsonc(content: string): T { - try { - return JSON.parse(stripJsonComments(content)) as T - } catch (e) { - throw new Error(`Failed to parse JSONC: ${e instanceof Error ? e.message : String(e)}`) - } -} +export { parseJsonc } from '@opencode-manager/shared/utils' export function hasJsoncComments(content: string): boolean { return content.split('\n').some(line => { diff --git a/shared/package.json b/shared/package.json index 9c25693e..1f3081e7 100644 --- a/shared/package.json +++ b/shared/package.json @@ -13,7 +13,8 @@ "./config": "./src/config/index.ts", "./config/defaults": "./src/config/defaults.ts", "./config/env": "./src/config/env.ts", - "./config/client": "./src/config/client.ts" + "./config/client": "./src/config/client.ts", + "./utils": "./src/utils/index.ts" }, "dependencies": { "zod": "^4.1.12" diff --git a/shared/src/index.ts b/shared/src/index.ts index c45b82fa..9532212a 100644 --- a/shared/src/index.ts +++ b/shared/src/index.ts @@ -1,3 +1,4 @@ export * from './config' export * from './schemas' export * from './types' +export * from './utils' diff --git a/shared/src/schemas/settings.ts b/shared/src/schemas/settings.ts index 4acd8f9f..db238a1c 100644 --- a/shared/src/schemas/settings.ts +++ b/shared/src/schemas/settings.ts @@ -198,7 +198,7 @@ export const OpenCodeConfigSchema = z.object({ disabled_providers: z.array(z.string()).optional(), share: z.enum(["manual", "auto", "disabled"]).optional(), plugin: z.array(z.string()).optional(), -}); +}).strip(); export type OpenCodeConfigContent = z.infer; diff --git a/shared/src/utils/index.ts b/shared/src/utils/index.ts new file mode 100644 index 00000000..89f7368b --- /dev/null +++ b/shared/src/utils/index.ts @@ -0,0 +1 @@ +export * from './jsonc' diff --git a/shared/src/utils/jsonc.ts b/shared/src/utils/jsonc.ts new file mode 100644 index 00000000..6d3f5f89 --- /dev/null +++ b/shared/src/utils/jsonc.ts @@ -0,0 +1,45 @@ +import { parse as parseJsoncLib, type ParseError } from 'jsonc-parser' + +export function parseJsonc(content: string): T { + const errors: ParseError[] = [] + const result = parseJsoncLib(content, errors, { + allowTrailingComma: true, + disallowComments: false, + }) + + if (errors.length > 0) { + const error = errors[0]! + const message = getParseErrorMessage(error.error, content, error.offset) + throw new SyntaxError(message) + } + + return result as T +} + +export function getParseErrorMessage(error: number, content: string, offset: number | undefined): string { + if (offset === undefined) { + return getErrorMessageByCode(error) + } + + const line = content.substring(0, offset).split('\n').length + const col = (content.substring(0, offset).split('\n').pop()?.length ?? 0) + 1 + + const message = getErrorMessageByCode(error) + return `${message} at line ${line}, column ${col}` +} + +function getErrorMessageByCode(error: number): string { + const errorMessages: Record = { + 1: 'Invalid symbol', + 2: 'Invalid number format', + 3: 'Property name expected', + 4: 'Value expected', + 5: 'Colon expected', + 6: 'Comma expected', + 7: 'Trailing comma not allowed', + 8: 'Unexpected end of input', + 9: 'Invalid comment', + } + + return errorMessages[error] || 'Invalid JSONC' +}