39 lines
1.2 KiB
TypeScript
39 lines
1.2 KiB
TypeScript
import { readFileSync, existsSync } from 'node:fs';
|
|
|
|
export type LoadRestoreKeysStatus = 'ok' | 'missing' | 'invalid';
|
|
|
|
export interface LoadRestoreKeysResult {
|
|
keys: Map<string, string>;
|
|
status: LoadRestoreKeysStatus;
|
|
count: number;
|
|
path: string;
|
|
}
|
|
|
|
export function loadRestoreKeys(path: string): LoadRestoreKeysResult {
|
|
if (!existsSync(path)) {
|
|
return { keys: new Map(), status: 'missing', count: 0, path };
|
|
}
|
|
let raw: string;
|
|
try {
|
|
raw = readFileSync(path, 'utf8');
|
|
} catch {
|
|
return { keys: new Map(), status: 'invalid', count: 0, path };
|
|
}
|
|
let parsed: unknown;
|
|
try {
|
|
parsed = JSON.parse(raw);
|
|
} catch {
|
|
return { keys: new Map(), status: 'invalid', count: 0, path };
|
|
}
|
|
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
|
|
return { keys: new Map(), status: 'invalid', count: 0, path };
|
|
}
|
|
const entries: Array<[string, string]> = [];
|
|
for (const [filename, key] of Object.entries(parsed as Record<string, unknown>)) {
|
|
if (typeof key === 'string' && key.length > 0) {
|
|
entries.push([filename, key]);
|
|
}
|
|
}
|
|
const keys = new Map(entries);
|
|
return { keys, status: 'ok', count: keys.size, path };
|
|
}
|