File size: 1,684 Bytes
1794757
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
type RuntimeEnv = {
  apiBaseUrl: string;
  vercelApiBase: string;
  enableSourceLogic: boolean;
};

declare global {
  interface Window {
    __trenchesEnv?: Partial<Record<keyof RuntimeEnv | "mapboxToken", string | boolean>>;
  }
}

function toBoolean(value: string | boolean | undefined, fallback: boolean): boolean {
  if (typeof value === "boolean") {
    return value;
  }
  if (typeof value !== "string") {
    return fallback;
  }
  return value.toLowerCase() === "true";
}

function readClientEnv(key: keyof RuntimeEnv | "mapboxToken"): string | boolean | undefined {
  if (typeof window !== "undefined" && window.__trenchesEnv && key in window.__trenchesEnv) {
    return window.__trenchesEnv[key];
  }
  return undefined;
}

export function getRuntimeEnv(): RuntimeEnv {
  const clientApiBase = readClientEnv("apiBaseUrl");
  const clientVercelBase = readClientEnv("vercelApiBase");
  const clientSourceLogic = readClientEnv("enableSourceLogic");
  return {
    apiBaseUrl: (typeof clientApiBase === "string" ? clientApiBase : process.env.NEXT_PUBLIC_API_BASE_URL) || "http://localhost:8000",
    vercelApiBase: (typeof clientVercelBase === "string" ? clientVercelBase : process.env.NEXT_PUBLIC_VERCEL_API_BASE) || "/api",
    enableSourceLogic: toBoolean(
      typeof clientSourceLogic === "string" || typeof clientSourceLogic === "boolean"
        ? clientSourceLogic
        : process.env.NEXT_PUBLIC_ENABLE_SOURCE_LOGIC,
      false,
    ),
  };
}

export function getMapboxToken(): string {
  const clientToken = readClientEnv("mapboxToken");
  if (typeof clientToken === "string") {
    return clientToken;
  }
  return process.env.NEXT_PUBLIC_MAPBOX_TOKEN || "";
}