| 1 | let current = Object.freeze({ mode: "none", connection_id: "" }); |
| 2 | |
| 3 | export function setClientContext(value) { |
| 4 | current = Object.freeze({ ...value }); |
| 5 | } |
| 6 | |
| 7 | export const getClientContext = () => current; |
| 8 | export const isRemoteClient = () => current.mode === "remote"; |
| 9 | |
| 10 | export function assertConnection(connectionID) { |
| 11 | if (current.connection_id !== connectionID) { |
| 12 | const error = new Error("工作环境已切换,请在当前环境重新操作。"); |
| 13 | error.code = "connection_changed"; |
| 14 | throw error; |
| 15 | } |
| 16 | } |
| 17 | |
| 18 | export function connectionHeaders(path, context = current) { |
| 19 | if (path === "/session" || (path.startsWith("/client/") && !isProjectSharesPath(path))) return {}; |
| 20 | return { "X-Cage-Connection": context.connection_id || "disconnected" }; |
| 21 | } |
| 22 | |
| 23 | export const isProjectSharesPath = (path) => path === "/client/project-shares" || path.startsWith("/client/project-shares/"); |
| 24 | |
| 25 | export function runtimeURL(path, context = current) { |
| 26 | const url = new URL("/api" + path, globalThis.location?.origin || "http://localhost"); |
| 27 | url.searchParams.set("connection", context.connection_id || "disconnected"); |
| 28 | return url.pathname + url.search; |
| 29 | } |
| 30 | |
| 31 | export function runtimeSocketURL(path, context = current) { |
| 32 | return `${location.protocol === "https:" ? "wss" : "ws"}://${location.host}${runtimeURL(path, context)}`; |
| 33 | } |
| 34 | |
| 35 | export function clientStorageKey(key, context = current) { |
| 36 | return context.mode === "remote" |
| 37 | ? `${key}:remote:${context.instance_id || context.host_id || "disconnected"}` |
| 38 | : key; |
| 39 | } |
| 40 | |
| 41 | export function clientKeyboard(serverKeyboard, context = current) { |
| 42 | if (context.mode !== "remote") return serverKeyboard; |
| 43 | try { |
| 44 | const saved = localStorage.getItem(clientStorageKey("cage-keyboard", context)); |
| 45 | if (["mac", "native"].includes(saved)) return saved; |
| 46 | } catch { } |
| 47 | return context.client_platform === "darwin" ? "mac" : "native"; |
| 48 | } |
| 49 | |
| 50 | export function saveClientKeyboard(value) { |
| 51 | if (!["mac", "native"].includes(value)) throw new Error("键盘习惯无效"); |
| 52 | localStorage.setItem(clientStorageKey("cage-keyboard"), value); |
| 53 | window.dispatchEvent(new Event("cage-client-preferences")); |
| 54 | } |