File
Blob: src/client/lib/client-config.ts
| 1 | import type { PublicClientConfig } from "@/shared/types"; |
| 2 | |
| 3 | declare global { |
| 4 | interface Window { |
| 5 | __BLAND_PUBLIC_CONFIG__?: unknown; |
| 6 | __BLAND_CSP_NONCE__?: unknown; |
| 7 | } |
| 8 | } |
| 9 | |
| 10 | type ClientConfigState = { |
| 11 | config: PublicClientConfig | null; |
| 12 | error: Error | null; |
| 13 | }; |
| 14 | |
| 15 | let clientConfigState: ClientConfigState | null = null; |
| 16 | |
| 17 | function isPublicClientConfig(rawConfig: unknown): rawConfig is PublicClientConfig { |
| 18 | if (!rawConfig || typeof rawConfig !== "object") { |
| 19 | return false; |
| 20 | } |
| 21 | |
| 22 | const value = rawConfig as Record<string, unknown>; |
| 23 | const sentryDsn = value.sentry_dsn; |
| 24 | |
| 25 | return sentryDsn === null || (typeof sentryDsn === "string" && sentryDsn.length > 0); |
| 26 | } |
| 27 | |
| 28 | function resolveClientConfigState(): ClientConfigState { |
| 29 | if (clientConfigState) { |
| 30 | return clientConfigState; |
| 31 | } |
| 32 | |
| 33 | const rawConfig = typeof window === "undefined" ? undefined : window.__BLAND_PUBLIC_CONFIG__; |
| 34 | if (rawConfig === undefined) { |
| 35 | clientConfigState = { |
| 36 | config: null, |
| 37 | error: new Error("Missing Worker bootstrap config"), |
| 38 | }; |
| 39 | return clientConfigState; |
| 40 | } |
| 41 | |
| 42 | if (!isPublicClientConfig(rawConfig)) { |
| 43 | clientConfigState = { |
| 44 | config: null, |
| 45 | error: new Error("Invalid Worker bootstrap config"), |
| 46 | }; |
| 47 | return clientConfigState; |
| 48 | } |
| 49 | |
| 50 | clientConfigState = { |
| 51 | config: rawConfig, |
| 52 | error: null, |
| 53 | }; |
| 54 | return clientConfigState; |
| 55 | } |
| 56 | |
| 57 | export function getClientConfigSnapshot(): PublicClientConfig | null { |
| 58 | return resolveClientConfigState().config; |
| 59 | } |
| 60 | |
| 61 | export function getClientConfigErrorSnapshot(): Error | null { |
| 62 | return resolveClientConfigState().error; |
| 63 | } |
| 64 | |
| 65 | export function getBootstrapCspNonceSnapshot(): string | null { |
| 66 | if (typeof window === "undefined") return null; |
| 67 | return typeof window.__BLAND_CSP_NONCE__ === "string" && window.__BLAND_CSP_NONCE__.length > 0 |
| 68 | ? window.__BLAND_CSP_NONCE__ |
| 69 | : null; |
| 70 | } |