mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-05 12:24:30 +01:00
Replace strip-json-comments with jsonc-parser for better error reporting
This commit is contained in:
1 parent
e1890d0554
commit
e1a4a70d3d
13 files changed
+132
-34
No files matched your search
@@ -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"
|
||||
},
|
||||
|
||||
@@ -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<void> {
|
||||
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<void> {
|
||||
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) {
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -8,13 +8,34 @@ interface FetchWrapperOptions extends RequestInit {
|
||||
params?: Record<string, string | number | boolean | undefined>
|
||||
}
|
||||
|
||||
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<string, unknown>).path)
|
||||
? ((d as Record<string, unknown>).path as string[])
|
||||
: undefined
|
||||
const message = typeof (d as Record<string, unknown>).message === 'string'
|
||||
? (d as Record<string, unknown>).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<never> {
|
||||
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
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -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<Record<string, unknown>>(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<Record<string, unknown>>(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 && (
|
||||
<div className="absolute bottom-0 left-0 right-0 bg-background/95 border-t p-2 sm:p-3">
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
@@ -1,12 +1,4 @@
|
||||
import stripJsonComments from 'strip-json-comments'
|
||||
|
||||
export function parseJsonc<T = unknown>(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 => {
|
||||
|
||||
+2
-1
@@ -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"
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
export * from './config'
|
||||
export * from './schemas'
|
||||
export * from './types'
|
||||
export * from './utils'
|
||||
@@ -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<typeof OpenCodeConfigSchema>;
|
||||
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
export * from './jsonc'
|
||||
@@ -0,0 +1,45 @@
|
||||
import { parse as parseJsoncLib, type ParseError } from 'jsonc-parser'
|
||||
|
||||
export function parseJsonc<T = unknown>(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<number, string> = {
|
||||
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'
|
||||
}
|
||||
Reference in new issue
Block a user