mirror of
https://gitlab.com/soapbox-pub/shakespeare.git
synced 2026-12-03 07:57:22 +00:00
Remove legacy migrations from configUtils, parse with zod
This commit is contained in:
4 files changed
+201
-171
No files matched your search
@@ -61,7 +61,7 @@ describe('configUtils', () => {
|
||||
apiKey: 'sk-test123',
|
||||
},
|
||||
],
|
||||
recentlyUsedModels: ['gpt-4', 'gpt-3.5-turbo'],
|
||||
recentlyUsedModels: ['openai/gpt-4', 'openai/gpt-3.5-turbo'],
|
||||
};
|
||||
|
||||
describe('readAISettings', () => {
|
||||
@@ -97,26 +97,6 @@ describe('configUtils', () => {
|
||||
recentlyUsedModels: [],
|
||||
});
|
||||
});
|
||||
|
||||
it('should migrate from localStorage if VFS file does not exist', async () => {
|
||||
vi.mocked(mockFS.readFile).mockRejectedValue(new Error('File not found'));
|
||||
vi.mocked(mockFS.stat).mockRejectedValue(new Error('Directory not found'));
|
||||
vi.mocked(mockFS.mkdir).mockResolvedValue(undefined);
|
||||
vi.mocked(mockFS.writeFile).mockResolvedValue(undefined);
|
||||
|
||||
mockLocalStorage.getItem.mockReturnValue(JSON.stringify(sampleAISettings));
|
||||
|
||||
const result = await readAISettings(mockFS);
|
||||
|
||||
expect(result).toEqual(sampleAISettings);
|
||||
expect(mockLocalStorage.getItem).toHaveBeenCalledWith('ai-settings');
|
||||
expect(mockLocalStorage.removeItem).toHaveBeenCalledWith('ai-settings');
|
||||
expect(mockFS.writeFile).toHaveBeenCalledWith(
|
||||
'/config/ai.json',
|
||||
JSON.stringify(sampleAISettings, null, 2),
|
||||
'utf8'
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('writeAISettings', () => {
|
||||
@@ -188,26 +168,6 @@ describe('configUtils', () => {
|
||||
corsProxy: 'https://proxy.shakespeare.diy/?url={href}',
|
||||
});
|
||||
});
|
||||
|
||||
it('should migrate from localStorage if VFS file does not exist', async () => {
|
||||
vi.mocked(mockFS.readFile).mockRejectedValue(new Error('File not found'));
|
||||
vi.mocked(mockFS.stat).mockRejectedValue(new Error('Directory not found'));
|
||||
vi.mocked(mockFS.mkdir).mockResolvedValue(undefined);
|
||||
vi.mocked(mockFS.writeFile).mockResolvedValue(undefined);
|
||||
|
||||
mockLocalStorage.getItem.mockReturnValue(JSON.stringify(sampleGitSettings));
|
||||
|
||||
const result = await readGitSettings(mockFS);
|
||||
|
||||
expect(result).toEqual(sampleGitSettings);
|
||||
expect(mockLocalStorage.getItem).toHaveBeenCalledWith('git-settings');
|
||||
expect(mockLocalStorage.removeItem).toHaveBeenCalledWith('git-settings');
|
||||
expect(mockFS.writeFile).toHaveBeenCalledWith(
|
||||
'/config/git.json',
|
||||
JSON.stringify(sampleGitSettings, null, 2),
|
||||
'utf8'
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('writeGitSettings', () => {
|
||||
|
||||
+39
-130
@@ -1,11 +1,40 @@
|
||||
import z from 'zod';
|
||||
import { filteredArray } from '@/lib/schema';
|
||||
import type { JSRuntimeFS } from '@/lib/JSRuntime';
|
||||
import type { AISettings, AIProvider } from '@/contexts/AISettingsContext';
|
||||
import type { AIProvider, AISettings } from '@/contexts/AISettingsContext';
|
||||
import type { GitSettings } from '@/contexts/GitSettingsContext';
|
||||
|
||||
const CONFIG_DIR = '/config';
|
||||
const AI_CONFIG_PATH = `${CONFIG_DIR}/ai.json`;
|
||||
const GIT_CONFIG_PATH = `${CONFIG_DIR}/git.json`;
|
||||
|
||||
const aiProviderSchema: z.ZodType<AIProvider> = z.object({
|
||||
id: z.string(),
|
||||
baseURL: z.string().url(),
|
||||
apiKey: z.string().optional(),
|
||||
nostr: z.boolean().optional(),
|
||||
});
|
||||
|
||||
const providerModelSchema = z.string().regex(
|
||||
/^[^/]+\/.+$/,
|
||||
'Must be in format provider/model (e.g., "openai/gpt-4o")',
|
||||
);
|
||||
|
||||
const aiSettingsSchema = z.object({
|
||||
providers: filteredArray(aiProviderSchema),
|
||||
recentlyUsedModels: filteredArray(providerModelSchema),
|
||||
});
|
||||
|
||||
const gitCredentialSchema = z.object({
|
||||
username: z.string(),
|
||||
password: z.string(),
|
||||
});
|
||||
|
||||
const gitSettingsSchema = z.object({
|
||||
credentials: z.record(z.string(), gitCredentialSchema),
|
||||
corsProxy: z.string().url().catch('https://proxy.shakespeare.diy/?url={href}')
|
||||
});
|
||||
|
||||
/**
|
||||
* Ensures the config directory exists
|
||||
*/
|
||||
@@ -17,49 +46,6 @@ async function ensureConfigDir(fs: JSRuntimeFS): Promise<void> {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Migrate AI settings from localStorage to VFS (internal function)
|
||||
*/
|
||||
async function migrateAISettingsFromLocalStorage(fs: JSRuntimeFS): Promise<AISettings | null> {
|
||||
// If not in VFS, try to migrate from localStorage
|
||||
const stored = localStorage.getItem('ai-settings');
|
||||
if (stored) {
|
||||
try {
|
||||
const parsed = JSON.parse(stored);
|
||||
if (parsed && typeof parsed === 'object' && 'providers' in parsed) {
|
||||
// Handle migration from old map format to new array format
|
||||
let providers;
|
||||
if (Array.isArray(parsed.providers)) {
|
||||
providers = parsed.providers;
|
||||
} else if (parsed.providers && typeof parsed.providers === 'object') {
|
||||
// Convert map to array
|
||||
providers = Object.entries(parsed.providers).map(([id, connection]) => ({
|
||||
id,
|
||||
...(connection as Omit<AIProvider, 'id'>),
|
||||
}));
|
||||
} else {
|
||||
providers = [];
|
||||
}
|
||||
|
||||
const settings: AISettings = {
|
||||
providers,
|
||||
recentlyUsedModels: parsed.recentlyUsedModels || [],
|
||||
};
|
||||
|
||||
// Write to VFS and remove from localStorage
|
||||
await writeAISettings(fs, settings);
|
||||
localStorage.removeItem('ai-settings');
|
||||
|
||||
return settings;
|
||||
}
|
||||
} catch {
|
||||
// If parsing fails, return null
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Read AI settings from VFS (with automatic migration from localStorage)
|
||||
*/
|
||||
@@ -69,50 +55,16 @@ export async function readAISettings(fs: JSRuntimeFS): Promise<AISettings> {
|
||||
recentlyUsedModels: [],
|
||||
};
|
||||
|
||||
// Try to read from VFS first
|
||||
try {
|
||||
const content = await fs.readFile(AI_CONFIG_PATH, 'utf8');
|
||||
const parsed = JSON.parse(content);
|
||||
|
||||
if (parsed && typeof parsed === 'object' && 'providers' in parsed) {
|
||||
// Handle migration from old map format to new array format
|
||||
let providers;
|
||||
if (Array.isArray(parsed.providers)) {
|
||||
providers = parsed.providers;
|
||||
} else if (parsed.providers && typeof parsed.providers === 'object') {
|
||||
// Convert map to array
|
||||
providers = Object.entries(parsed.providers).map(([id, connection]) => ({
|
||||
id,
|
||||
...(connection as Omit<AIProvider, 'id'>),
|
||||
}));
|
||||
|
||||
// Write back the migrated format
|
||||
const migratedSettings: AISettings = {
|
||||
providers,
|
||||
recentlyUsedModels: parsed.recentlyUsedModels || [],
|
||||
};
|
||||
await writeAISettings(fs, migratedSettings);
|
||||
return migratedSettings;
|
||||
} else {
|
||||
providers = [];
|
||||
}
|
||||
|
||||
return {
|
||||
providers,
|
||||
recentlyUsedModels: parsed.recentlyUsedModels || [],
|
||||
};
|
||||
const data = JSON.parse(content);
|
||||
return aiSettingsSchema.parse(data);
|
||||
} catch (error) {
|
||||
if (error instanceof z.ZodError) {
|
||||
console.error('AI settings parsing error:', error.errors);
|
||||
}
|
||||
} catch {
|
||||
// File doesn't exist or is invalid, try migration
|
||||
return defaultSettings;
|
||||
}
|
||||
|
||||
// If not in VFS, try to migrate from localStorage
|
||||
const migratedSettings = await migrateAISettingsFromLocalStorage(fs);
|
||||
if (migratedSettings) {
|
||||
return migratedSettings;
|
||||
}
|
||||
|
||||
return defaultSettings;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -123,35 +75,6 @@ export async function writeAISettings(fs: JSRuntimeFS, settings: AISettings): Pr
|
||||
await fs.writeFile(AI_CONFIG_PATH, JSON.stringify(settings, null, 2), 'utf8');
|
||||
}
|
||||
|
||||
/**
|
||||
* Migrate Git settings from localStorage to VFS (internal function)
|
||||
*/
|
||||
async function migrateGitSettingsFromLocalStorage(fs: JSRuntimeFS): Promise<GitSettings | null> {
|
||||
// If not in VFS, try to migrate from localStorage
|
||||
const stored = localStorage.getItem('git-settings');
|
||||
if (stored) {
|
||||
try {
|
||||
const parsed = JSON.parse(stored);
|
||||
if (parsed && typeof parsed === 'object' && 'credentials' in parsed) {
|
||||
const settings: GitSettings = {
|
||||
credentials: parsed.credentials || {},
|
||||
corsProxy: parsed.corsProxy || 'https://proxy.shakespeare.diy/?url={href}',
|
||||
};
|
||||
|
||||
// Write to VFS and remove from localStorage
|
||||
await writeGitSettings(fs, settings);
|
||||
localStorage.removeItem('git-settings');
|
||||
|
||||
return settings;
|
||||
}
|
||||
} catch {
|
||||
// If parsing fails, return null
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Read Git settings from VFS (with automatic migration from localStorage)
|
||||
*/
|
||||
@@ -164,25 +87,11 @@ export async function readGitSettings(fs: JSRuntimeFS): Promise<GitSettings> {
|
||||
// Try to read from VFS first
|
||||
try {
|
||||
const content = await fs.readFile(GIT_CONFIG_PATH, 'utf8');
|
||||
const parsed = JSON.parse(content);
|
||||
|
||||
if (parsed && typeof parsed === 'object' && 'credentials' in parsed) {
|
||||
return {
|
||||
credentials: parsed.credentials || {},
|
||||
corsProxy: parsed.corsProxy || 'https://proxy.shakespeare.diy/?url={href}',
|
||||
};
|
||||
}
|
||||
const data = JSON.parse(content);
|
||||
return gitSettingsSchema.parse(data);
|
||||
} catch {
|
||||
// File doesn't exist or is invalid, try migration
|
||||
return defaultSettings;
|
||||
}
|
||||
|
||||
// If not in VFS, try to migrate from localStorage
|
||||
const migratedSettings = await migrateGitSettingsFromLocalStorage(fs);
|
||||
if (migratedSettings) {
|
||||
return migratedSettings;
|
||||
}
|
||||
|
||||
return defaultSettings;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -0,0 +1,149 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import z from 'zod';
|
||||
import { filteredArray } from './schema';
|
||||
|
||||
describe('filteredArray', () => {
|
||||
it('filters out invalid items and keeps valid ones', () => {
|
||||
const numberSchema = z.number();
|
||||
const schema = filteredArray(numberSchema);
|
||||
|
||||
const input = [1, 'invalid', 2, null, 3, undefined, 4];
|
||||
const result = schema.parse(input);
|
||||
|
||||
expect(result).toEqual([1, 2, 3, 4]);
|
||||
});
|
||||
|
||||
it('returns empty array when all items are invalid', () => {
|
||||
const numberSchema = z.number();
|
||||
const schema = filteredArray(numberSchema);
|
||||
|
||||
const input = ['string', null, undefined, {}, []];
|
||||
const result = schema.parse(input);
|
||||
|
||||
expect(result).toEqual([]);
|
||||
});
|
||||
|
||||
it('returns all items when all are valid', () => {
|
||||
const stringSchema = z.string();
|
||||
const schema = filteredArray(stringSchema);
|
||||
|
||||
const input = ['hello', 'world', 'test'];
|
||||
const result = schema.parse(input);
|
||||
|
||||
expect(result).toEqual(['hello', 'world', 'test']);
|
||||
});
|
||||
|
||||
it('works with complex object schemas', () => {
|
||||
const userSchema = z.object({
|
||||
id: z.number(),
|
||||
name: z.string(),
|
||||
email: z.string().email(),
|
||||
});
|
||||
const schema = filteredArray(userSchema);
|
||||
|
||||
const input = [
|
||||
{ id: 1, name: 'John', email: '[email protected]' },
|
||||
{ id: 'invalid', name: 'Jane', email: '[email protected]' }, // invalid id
|
||||
{ id: 2, name: 'Bob', email: 'invalid-email' }, // invalid email
|
||||
{ id: 3, name: 'Alice', email: '[email protected]' },
|
||||
'not an object',
|
||||
null,
|
||||
];
|
||||
|
||||
const result = schema.parse(input);
|
||||
|
||||
expect(result).toEqual([
|
||||
{ id: 1, name: 'John', email: '[email protected]' },
|
||||
{ id: 3, name: 'Alice', email: '[email protected]' },
|
||||
]);
|
||||
});
|
||||
|
||||
it('handles empty array input', () => {
|
||||
const numberSchema = z.number();
|
||||
const schema = filteredArray(numberSchema);
|
||||
|
||||
const result = schema.parse([]);
|
||||
|
||||
expect(result).toEqual([]);
|
||||
});
|
||||
|
||||
it('catches non-array input and returns empty array', () => {
|
||||
const numberSchema = z.number();
|
||||
const schema = filteredArray(numberSchema);
|
||||
|
||||
const result1 = schema.parse('not an array');
|
||||
const result2 = schema.parse(null);
|
||||
const result3 = schema.parse(undefined);
|
||||
const result4 = schema.parse(123);
|
||||
|
||||
expect(result1).toEqual([]);
|
||||
expect(result2).toEqual([]);
|
||||
expect(result3).toEqual([]);
|
||||
expect(result4).toEqual([]);
|
||||
});
|
||||
|
||||
it('works with union schemas', () => {
|
||||
const unionSchema = z.union([z.string(), z.number()]);
|
||||
const schema = filteredArray(unionSchema);
|
||||
|
||||
const input = ['hello', 42, true, 'world', null, 99, {}];
|
||||
const result = schema.parse(input);
|
||||
|
||||
expect(result).toEqual(['hello', 42, 'world', 99]);
|
||||
});
|
||||
|
||||
it('preserves transformed values from schema', () => {
|
||||
const transformSchema = z.string().transform((str) => str.toUpperCase());
|
||||
const schema = filteredArray(transformSchema);
|
||||
|
||||
const input = ['hello', 123, 'world', null, 'test'];
|
||||
const result = schema.parse(input);
|
||||
|
||||
expect(result).toEqual(['HELLO', 'WORLD', 'TEST']);
|
||||
});
|
||||
|
||||
it('works with optional fields in object schemas', () => {
|
||||
const optionalSchema = z.object({
|
||||
required: z.string(),
|
||||
optional: z.string().optional(),
|
||||
});
|
||||
const schema = filteredArray(optionalSchema);
|
||||
|
||||
const input = [
|
||||
{ required: 'test1' },
|
||||
{ required: 'test2', optional: 'value' },
|
||||
{ optional: 'value' }, // missing required field
|
||||
{ required: 'test3', optional: undefined },
|
||||
];
|
||||
|
||||
const result = schema.parse(input);
|
||||
|
||||
expect(result).toEqual([
|
||||
{ required: 'test1' },
|
||||
{ required: 'test2', optional: 'value' },
|
||||
{ required: 'test3', optional: undefined },
|
||||
]);
|
||||
});
|
||||
|
||||
it('handles nested arrays', () => {
|
||||
const nestedSchema = z.object({
|
||||
name: z.string(),
|
||||
tags: z.string().array(),
|
||||
});
|
||||
const schema = filteredArray(nestedSchema);
|
||||
|
||||
const input = [
|
||||
{ name: 'item1', tags: ['tag1', 'tag2'] },
|
||||
{ name: 'item2', tags: 'not an array' }, // invalid tags
|
||||
{ name: 'item3', tags: [] },
|
||||
'invalid item',
|
||||
];
|
||||
|
||||
const result = schema.parse(input);
|
||||
|
||||
expect(result).toEqual([
|
||||
{ name: 'item1', tags: ['tag1', 'tag2'] },
|
||||
{ name: 'item3', tags: [] },
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,12 @@
|
||||
import z from "zod";
|
||||
|
||||
/** Validates individual items in an array, dropping any that aren't valid. */
|
||||
export function filteredArray<T extends z.ZodTypeAny>(schema: T) {
|
||||
return z.any().array().catch([])
|
||||
.transform((arr) => (
|
||||
arr.map((item) => {
|
||||
const parsed = schema.safeParse(item);
|
||||
return parsed.success ? parsed.data : undefined;
|
||||
}).filter((item): item is z.infer<T> => Boolean(item))
|
||||
));
|
||||
}
|
||||
Reference in new issue
Block a user