import { stat } from 'node:fs/promises'; import { dirname, isAbsolute, join, resolve } from 'node:path'; import { readJsonOr, writeJsonAtomic } from './atomic-json.ts'; /** * Remembers the last directory chosen in native open/save dialogs, keyed by dialog category, * persisted to `/dialog-paths.json`. Read/write errors are swallowed so dialog * behavior is never disrupted. */ export type DialogPathCategory = | 'folder' | 'save-archive' | 'official-backups' | 'mods-folder' | 'mod-preset'; export interface DialogPathStore { resolveDialogDefaultPath( category: DialogPathCategory, explicitPath?: string | null, ): Promise; rememberDialogPath(category: DialogPathCategory, selectedPath: string): Promise; } const DIALOG_PATHS_FILENAME = 'dialog-paths.json'; const LAST_KEY = 'last'; const MAX_ANCESTOR_STEPS = 128; /** * Resolve `candidate` to an existing directory: * - If it is an existing directory, return its normalized path. * - If it is an existing file or does not exist, walk up to the nearest existing ancestor directory. * - Return `undefined` when no existing ancestor directory can be reached. */ export async function resolveExistingDirectory(candidate: string | null | undefined): Promise { if (!candidate) return undefined; const trimmed = candidate.trim(); if (!trimmed || !isAbsolute(trimmed)) return undefined; let current = resolve(trimmed); for (let step = 0; step < MAX_ANCESTOR_STEPS; step++) { try { const info = await stat(current); if (info.isDirectory()) return current; } catch { // Missing or inaccessible path; continue walking toward the filesystem root. } const parent = dirname(current); if (parent === current) return undefined; current = parent; } return undefined; } /** Create a dialog-path store backed by the JSON file path returned by `resolveStorePath`. */ export function createDialogPathStore( resolveStorePath: () => Promise | string | null, ): DialogPathStore { let cached: Map | null = null; let loading: Promise> | null = null; let pending: Promise = Promise.resolve(); async function loadMap(): Promise> { if (cached) return cached; if (loading) return loading; loading = (async () => { const map = new Map(); const storePath = await resolveStorePath(); if (storePath) { try { const raw = await readJsonOr(storePath, null); if (raw && typeof raw === 'object' && !Array.isArray(raw)) { for (const [key, value] of Object.entries(raw as Record)) { if (typeof value === 'string' && value.trim().length > 0) { map.set(key, value); } } } } catch (error) { console.warn('[dialog-paths] failed to read dialog paths:', error); } } cached = map; return map; })().finally(() => { loading = null; }); return loading; } return { async resolveDialogDefaultPath( category: DialogPathCategory, explicitPath?: string | null, ): Promise { try { const explicitDir = await resolveExistingDirectory(explicitPath); if (explicitDir) return explicitDir; const map = await loadMap(); const categoryPath = map.get(category); if (categoryPath) { const resolved = await resolveExistingDirectory(categoryPath); if (resolved) return resolved; } const lastPath = map.get(LAST_KEY); if (lastPath && lastPath !== categoryPath) { const resolved = await resolveExistingDirectory(lastPath); if (resolved) return resolved; } } catch (error) { console.warn('[dialog-paths] failed to resolve default dialog path:', error); } return undefined; }, async rememberDialogPath(category: DialogPathCategory, selectedPath: string): Promise { const dir = await resolveExistingDirectory(selectedPath); if (!dir) return; const operation = pending.then(async () => { const map = await loadMap(); if (map.get(category) === dir && map.get(LAST_KEY) === dir) return; map.set(category, dir); map.set(LAST_KEY, dir); const storePath = await resolveStorePath(); if (!storePath) return; try { await writeJsonAtomic(storePath, Object.fromEntries(map)); } catch (error) { console.warn('[dialog-paths] failed to save dialog paths:', error); } }); pending = operation.then(() => undefined, () => undefined); await operation; }, }; } async function defaultStorePath(): Promise { try { const mod = await import('electron') as { readonly app?: { getPath?: (name: 'userData') => string }; readonly default?: { app?: { getPath?: (name: 'userData') => string } }; }; const electronApp = mod.app ?? mod.default?.app; if (typeof electronApp?.getPath !== 'function') return null; return join(electronApp.getPath('userData'), DIALOG_PATHS_FILENAME); } catch { return null; } } const defaultStore = createDialogPathStore(defaultStorePath); export function resolveDialogDefaultPath( category: DialogPathCategory, explicitPath?: string | null, ): Promise { return defaultStore.resolveDialogDefaultPath(category, explicitPath); } export function rememberDialogPath(category: DialogPathCategory, selectedPath: string): Promise { return defaultStore.rememberDialogPath(category, selectedPath); }