import { safeGlobalProp } from './imports'; // src/functions/read_utils/src/read_utils.ts /** * Reads a JSON file, either via Node’s fs (if available) * or via window.fetch in the browser. Never throws — returns * the parsed object or null on any error. */ export async function readJsonFile(relativeOrAbsolutePath: string): Promise { if (typeof window === 'undefined') { try { const { readFile } = await import('fs/promises'); const { isAbsolute, resolve } = await import('path'); const filePath = isAbsolute(relativeOrAbsolutePath) ? relativeOrAbsolutePath : resolve(import.meta.url ? new URL('.', import.meta.url).pathname : '', relativeOrAbsolutePath); const text = await readFile(filePath, 'utf8'); return JSON.parse(text) as T; } catch { return null; } } // Browser fallback const fetchFn = safeGlobalProp('fetch'); if (typeof fetchFn !== 'function') return null; let url = relativeOrAbsolutePath; const baseURI = safeGlobalProp('document', 'baseURI'); if (baseURI) { try { url = new URL(relativeOrAbsolutePath, baseURI).href; } catch {} } try { const res = await fetchFn(url); if (!res.ok) return null; return await res.json(); } catch { return null; } } export async function getConfigContent>(): Promise { try { // `readJsonFile` should throw if the file isn’t there or isn’t valid JSON const cfg = await readJsonFile('./config.json'); return cfg; } catch { // swallow errors & return null so callers can detect “no config” return null; } } // 2) Pull a single key out of that object export async function getConfigVar(key: any = null): Promise { const cfg = await getConfigContent>(); if (cfg && typeof cfg === 'object' && key in cfg) { return cfg[key] as T; } return undefined; }