import { Preferences } from "@capacitor/preferences";
const SERVER_URL_KEY = "shserv_server_url";
let _currentBaseUrl = "";
/**
* Detect if running inside a Capacitor native app (Android/iOS).
*/
export function isNativeApp() {
return typeof window !== "undefined" && window.Capacitor !== undefined;
}
/**
* Get the synchronous current base URL (set during app init).
*/
export function getCurrentBaseUrl() {
return _currentBaseUrl;
}
/**
* Set the in-memory base URL (used by http.js synchronously).
*/
export function setCurrentBaseUrl(url) {
_currentBaseUrl = String(url || "").replace(/\/+$/, "");
}
/**
* Load server URL from native Preferences (or env fallback for web).
* Call once during app startup.
*/
export async function initServerUrl() {
if (!isNativeApp()) {
setCurrentBaseUrl(import.meta.env.VITE_API_BASE_URL || "");
return;
}
try {
const { value } = await Preferences.get({ key: SERVER_URL_KEY });
setCurrentBaseUrl(value || "");
} catch {
setCurrentBaseUrl("");
}
}
/**
* Save the server URL for native app use.
*/
export async function setServerUrl(url) {
const clean = String(url || "").replace(/\/+$/, "");
setCurrentBaseUrl(clean);
if (!isNativeApp()) {
return;
}
try {
await Preferences.set({ key: SERVER_URL_KEY, value: clean });
} catch {
// ignore
}
}
/**
* Build an absolute URL to the server given a path.
* In web builds (same-origin) returns the path as-is.
* In native apps prepends the configured server URL.
*/
export function buildServerUrl(path) {
const base = getCurrentBaseUrl();
if (!base) {
return path;
}
const cleanPath = String(path || "").replace(/^\/+/, "");
return cleanPath ? `${base}/${cleanPath}` : base;
}
/**
* Check if native app has a configured server URL.
*/
export async function hasServerUrl() {
if (!isNativeApp()) {
return true;
}
const { value } = await Preferences.get({ key: SERVER_URL_KEY });
return !!value;
}