mirror of
https://github.com/anomalyco/opencode.git
synced 2026-08-07 17:33:26 +00:00
38 lines
1.1 KiB
TypeScript
38 lines
1.1 KiB
TypeScript
import { OpenCode, type OpenCodeClient } from "@opencode-ai/client/promise"
|
|
import type { ServerConnection } from "@/context/server"
|
|
import { decode64 } from "@/utils/base64"
|
|
|
|
export function authTokenFromCredentials(input: { username?: string; password: string }) {
|
|
return btoa(`${input.username ?? "opencode"}:${input.password}`)
|
|
}
|
|
|
|
export function authFromToken(token: string | null) {
|
|
const decoded = decode64(token ?? undefined)
|
|
if (!decoded) return
|
|
const separator = decoded.indexOf(":")
|
|
if (separator === -1) return
|
|
return {
|
|
username: decoded.slice(0, separator) || "opencode",
|
|
password: decoded.slice(separator + 1),
|
|
}
|
|
}
|
|
|
|
export function createApiForServer(input: {
|
|
server: ServerConnection.HttpBase
|
|
fetch?: typeof globalThis.fetch
|
|
}): OpenCodeClient {
|
|
return OpenCode.make({
|
|
baseUrl: input.server.url,
|
|
fetch: input.fetch,
|
|
headers: input.server.password
|
|
? {
|
|
Authorization: `Basic ${authTokenFromCredentials({
|
|
username: input.server.username,
|
|
password: input.server.password,
|
|
})}`,
|
|
}
|
|
: undefined,
|
|
})
|
|
}
|
|
|
|
export type ServerApi = OpenCodeClient
|