sdk v2
This commit is contained in:
parent
6667856ba5
commit
66a34798a4
61 changed files with 8856 additions and 1068 deletions
|
|
@ -29,7 +29,7 @@ import { MCP } from "@/mcp"
|
|||
import { Todo } from "@/session/todo"
|
||||
import { z } from "zod"
|
||||
import { LoadAPIKeyError } from "ai"
|
||||
import type { OpencodeClient } from "@opencode-ai/sdk"
|
||||
import type { OpencodeClient } from "@opencode-ai/sdk/v2"
|
||||
|
||||
export namespace ACP {
|
||||
const log = Log.create({ service: "acp-agent" })
|
||||
|
|
@ -68,7 +68,7 @@ export namespace ACP {
|
|||
{ optionId: "always", kind: "allow_always", name: "Always allow" },
|
||||
{ optionId: "reject", kind: "reject_once", name: "Reject" },
|
||||
]
|
||||
this.config.sdk.event.subscribe({ query: { directory } }).then(async (events) => {
|
||||
this.config.sdk.event.subscribe({ directory }).then(async (events) => {
|
||||
for await (const event of events.stream) {
|
||||
switch (event.type) {
|
||||
case "permission.updated":
|
||||
|
|
@ -93,32 +93,29 @@ export namespace ACP {
|
|||
permissionID: permission.id,
|
||||
sessionID: permission.sessionID,
|
||||
})
|
||||
await this.config.sdk.postSessionIdPermissionsPermissionId({
|
||||
path: { id: permission.sessionID, permissionID: permission.id },
|
||||
body: {
|
||||
response: "reject",
|
||||
},
|
||||
query: { directory },
|
||||
await this.config.sdk.permission.respond({
|
||||
sessionID: permission.sessionID,
|
||||
permissionID: permission.id,
|
||||
response: "reject",
|
||||
directory,
|
||||
})
|
||||
return
|
||||
})
|
||||
if (!res) return
|
||||
if (res.outcome.outcome !== "selected") {
|
||||
await this.config.sdk.postSessionIdPermissionsPermissionId({
|
||||
path: { id: permission.sessionID, permissionID: permission.id },
|
||||
body: {
|
||||
response: "reject",
|
||||
},
|
||||
query: { directory },
|
||||
await this.config.sdk.permission.respond({
|
||||
sessionID: permission.sessionID,
|
||||
permissionID: permission.id,
|
||||
response: "reject",
|
||||
directory,
|
||||
})
|
||||
return
|
||||
}
|
||||
await this.config.sdk.postSessionIdPermissionsPermissionId({
|
||||
path: { id: permission.sessionID, permissionID: permission.id },
|
||||
body: {
|
||||
response: res.outcome.optionId as "once" | "always" | "reject",
|
||||
},
|
||||
query: { directory },
|
||||
await this.config.sdk.permission.respond({
|
||||
sessionID: permission.sessionID,
|
||||
permissionID: permission.id,
|
||||
response: res.outcome.optionId as "once" | "always" | "reject",
|
||||
directory,
|
||||
})
|
||||
} catch (err) {
|
||||
log.error("unexpected error when handling permission", { error: err })
|
||||
|
|
@ -133,14 +130,14 @@ export namespace ACP {
|
|||
const { part } = props
|
||||
|
||||
const message = await this.config.sdk.session
|
||||
.message({
|
||||
throwOnError: true,
|
||||
path: {
|
||||
id: part.sessionID,
|
||||
.message(
|
||||
{
|
||||
sessionID: part.sessionID,
|
||||
messageID: part.messageID,
|
||||
directory,
|
||||
},
|
||||
query: { directory },
|
||||
})
|
||||
{ throwOnError: true },
|
||||
)
|
||||
.then((x) => x.data)
|
||||
.catch((err) => {
|
||||
log.error("unexpected error when fetching message", { error: err })
|
||||
|
|
@ -420,9 +417,7 @@ export namespace ACP {
|
|||
const model = await defaultModel(this.config, directory)
|
||||
const sessionId = params.sessionId
|
||||
|
||||
const providers = await this.sdk.config
|
||||
.providers({ throwOnError: true, query: { directory } })
|
||||
.then((x) => x.data.providers)
|
||||
const providers = await this.sdk.config.providers({ directory }).then((x) => x.data!.providers)
|
||||
const entries = providers.sort((a, b) => {
|
||||
const nameA = a.name.toLowerCase()
|
||||
const nameB = b.name.toLowerCase()
|
||||
|
|
@ -439,22 +434,22 @@ export namespace ACP {
|
|||
})
|
||||
|
||||
const agents = await this.config.sdk.app
|
||||
.agents({
|
||||
throwOnError: true,
|
||||
query: {
|
||||
.agents(
|
||||
{
|
||||
directory,
|
||||
},
|
||||
})
|
||||
.then((resp) => resp.data)
|
||||
{ throwOnError: true },
|
||||
)
|
||||
.then((resp) => resp.data!)
|
||||
|
||||
const commands = await this.config.sdk.command
|
||||
.list({
|
||||
throwOnError: true,
|
||||
query: {
|
||||
.list(
|
||||
{
|
||||
directory,
|
||||
},
|
||||
})
|
||||
.then((resp) => resp.data)
|
||||
{ throwOnError: true },
|
||||
)
|
||||
.then((resp) => resp.data!)
|
||||
|
||||
const availableCommands = commands.map((command) => ({
|
||||
name: command.name,
|
||||
|
|
@ -503,14 +498,14 @@ export namespace ACP {
|
|||
await Promise.all(
|
||||
Object.entries(mcpServers).map(async ([key, mcp]) => {
|
||||
await this.sdk.mcp
|
||||
.add({
|
||||
throwOnError: true,
|
||||
query: { directory },
|
||||
body: {
|
||||
.add(
|
||||
{
|
||||
directory,
|
||||
name: key,
|
||||
config: mcp,
|
||||
},
|
||||
})
|
||||
{ throwOnError: true },
|
||||
)
|
||||
.catch((error) => {
|
||||
log.error("failed to add mcp server", { name: key, error })
|
||||
})
|
||||
|
|
@ -559,7 +554,7 @@ export namespace ACP {
|
|||
async setSessionMode(params: SetSessionModeRequest): Promise<SetSessionModeResponse | void> {
|
||||
this.sessionManager.get(params.sessionId)
|
||||
await this.config.sdk.app
|
||||
.agents({ throwOnError: true })
|
||||
.agents({}, { throwOnError: true })
|
||||
.then((x) => x.data)
|
||||
.then((agent) => {
|
||||
if (!agent) throw new Error(`Agent not found: ${params.modeId}`)
|
||||
|
|
@ -651,50 +646,42 @@ export namespace ACP {
|
|||
|
||||
if (!cmd) {
|
||||
await this.sdk.session.prompt({
|
||||
path: { id: sessionID },
|
||||
body: {
|
||||
model: {
|
||||
providerID: model.providerID,
|
||||
modelID: model.modelID,
|
||||
},
|
||||
parts,
|
||||
agent,
|
||||
},
|
||||
query: {
|
||||
directory,
|
||||
sessionID,
|
||||
model: {
|
||||
providerID: model.providerID,
|
||||
modelID: model.modelID,
|
||||
},
|
||||
parts,
|
||||
agent,
|
||||
directory,
|
||||
})
|
||||
return done
|
||||
}
|
||||
|
||||
const command = await this.config.sdk.command
|
||||
.list({ throwOnError: true, query: { directory } })
|
||||
.then((x) => x.data.find((c) => c.name === cmd.name))
|
||||
.list({ directory }, { throwOnError: true })
|
||||
.then((x) => x.data!.find((c) => c.name === cmd.name))
|
||||
if (command) {
|
||||
await this.sdk.session.command({
|
||||
path: { id: sessionID },
|
||||
body: {
|
||||
command: command.name,
|
||||
arguments: cmd.args,
|
||||
model: model.providerID + "/" + model.modelID,
|
||||
agent,
|
||||
},
|
||||
query: {
|
||||
directory,
|
||||
},
|
||||
sessionID,
|
||||
command: command.name,
|
||||
arguments: cmd.args,
|
||||
model: model.providerID + "/" + model.modelID,
|
||||
agent,
|
||||
directory,
|
||||
})
|
||||
return done
|
||||
}
|
||||
|
||||
switch (cmd.name) {
|
||||
case "compact":
|
||||
await this.config.sdk.session.summarize({
|
||||
path: { id: sessionID },
|
||||
throwOnError: true,
|
||||
query: {
|
||||
await this.config.sdk.session.summarize(
|
||||
{
|
||||
sessionID,
|
||||
directory,
|
||||
},
|
||||
})
|
||||
{ throwOnError: true },
|
||||
)
|
||||
break
|
||||
}
|
||||
|
||||
|
|
@ -703,13 +690,13 @@ export namespace ACP {
|
|||
|
||||
async cancel(params: CancelNotification) {
|
||||
const session = this.sessionManager.get(params.sessionId)
|
||||
await this.config.sdk.session.abort({
|
||||
path: { id: params.sessionId },
|
||||
throwOnError: true,
|
||||
query: {
|
||||
await this.config.sdk.session.abort(
|
||||
{
|
||||
sessionID: params.sessionId,
|
||||
directory: session.cwd,
|
||||
},
|
||||
})
|
||||
{ throwOnError: true },
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -766,10 +753,10 @@ export namespace ACP {
|
|||
if (configured) return configured
|
||||
|
||||
const model = await sdk.config
|
||||
.get({ throwOnError: true, query: { directory: cwd } })
|
||||
.get({ directory: cwd }, { throwOnError: true })
|
||||
.then((resp) => {
|
||||
const cfg = resp.data
|
||||
if (!cfg.model) return undefined
|
||||
if (!cfg || !cfg.model) return undefined
|
||||
const parsed = Provider.parseModel(cfg.model)
|
||||
return {
|
||||
providerID: parsed.providerID,
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
import { RequestError, type McpServer } from "@agentclientprotocol/sdk"
|
||||
import type { ACPSessionState } from "./types"
|
||||
import { Log } from "@/util/log"
|
||||
import type { OpencodeClient } from "@opencode-ai/sdk"
|
||||
import type { OpencodeClient } from "@opencode-ai/sdk/v2"
|
||||
|
||||
const log = Log.create({ service: "acp-session-manager" })
|
||||
|
||||
|
|
@ -15,16 +15,14 @@ export class ACPSessionManager {
|
|||
|
||||
async create(cwd: string, mcpServers: McpServer[], model?: ACPSessionState["model"]): Promise<ACPSessionState> {
|
||||
const session = await this.sdk.session
|
||||
.create({
|
||||
body: {
|
||||
.create(
|
||||
{
|
||||
title: `ACP Session ${crypto.randomUUID()}`,
|
||||
},
|
||||
query: {
|
||||
directory: cwd,
|
||||
},
|
||||
throwOnError: true,
|
||||
})
|
||||
.then((x) => x.data)
|
||||
{ throwOnError: true },
|
||||
)
|
||||
.then((x) => x.data!)
|
||||
|
||||
const sessionId = session.id
|
||||
const resolvedModel = model
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
import type { McpServer } from "@agentclientprotocol/sdk"
|
||||
import type { OpencodeClient } from "@opencode-ai/sdk"
|
||||
import type { OpencodeClient } from "@opencode-ai/sdk/v2"
|
||||
|
||||
export interface ACPSessionState {
|
||||
id: string
|
||||
|
|
|
|||
|
|
@ -4,7 +4,7 @@ import { cmd } from "./cmd"
|
|||
import { AgentSideConnection, ndJsonStream } from "@agentclientprotocol/sdk"
|
||||
import { ACP } from "@/acp/agent"
|
||||
import { Server } from "@/server/server"
|
||||
import { createOpencodeClient } from "@opencode-ai/sdk"
|
||||
import { createOpencodeClient } from "@opencode-ai/sdk/v2"
|
||||
|
||||
const log = Log.create({ service: "acp-command" })
|
||||
|
||||
|
|
|
|||
|
|
@ -7,7 +7,7 @@ import { bootstrap } from "../bootstrap"
|
|||
import { Command } from "../../command"
|
||||
import { EOL } from "os"
|
||||
import { select } from "@clack/prompts"
|
||||
import { createOpencodeClient, type OpencodeClient } from "@opencode-ai/sdk"
|
||||
import { createOpencodeClient, type OpencodeClient } from "@opencode-ai/sdk/v2"
|
||||
import { Server } from "../../server/server"
|
||||
import { Provider } from "../../provider/provider"
|
||||
|
||||
|
|
@ -212,9 +212,10 @@ export const RunCommand = cmd({
|
|||
initialValue: "once",
|
||||
}).catch(() => "reject")
|
||||
const response = (result.toString().includes("cancel") ? "reject" : result) as "once" | "always" | "reject"
|
||||
await sdk.postSessionIdPermissionsPermissionId({
|
||||
path: { id: sessionID, permissionID: permission.id },
|
||||
body: { response },
|
||||
await sdk.permission.respond({
|
||||
sessionID,
|
||||
permissionID: permission.id,
|
||||
response,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
|
@ -222,23 +223,19 @@ export const RunCommand = cmd({
|
|||
|
||||
if (args.command) {
|
||||
await sdk.session.command({
|
||||
path: { id: sessionID },
|
||||
body: {
|
||||
agent: args.agent || "build",
|
||||
model: args.model,
|
||||
command: args.command,
|
||||
arguments: message,
|
||||
},
|
||||
sessionID,
|
||||
agent: args.agent || "build",
|
||||
model: args.model,
|
||||
command: args.command,
|
||||
arguments: message,
|
||||
})
|
||||
} else {
|
||||
const modelParam = args.model ? Provider.parseModel(args.model) : undefined
|
||||
await sdk.session.prompt({
|
||||
path: { id: sessionID },
|
||||
body: {
|
||||
agent: args.agent || "build",
|
||||
model: modelParam,
|
||||
parts: [...fileParts, { type: "text", text: message }],
|
||||
},
|
||||
sessionID,
|
||||
agent: args.agent || "build",
|
||||
model: modelParam,
|
||||
parts: [...fileParts, { type: "text", text: message }],
|
||||
})
|
||||
}
|
||||
|
||||
|
|
@ -263,7 +260,7 @@ export const RunCommand = cmd({
|
|||
: args.title
|
||||
: undefined
|
||||
|
||||
const result = await sdk.session.create({ body: title ? { title } : {} })
|
||||
const result = await sdk.session.create(title ? { title } : {})
|
||||
return result.data?.id
|
||||
})()
|
||||
|
||||
|
|
@ -274,7 +271,7 @@ export const RunCommand = cmd({
|
|||
|
||||
const cfgResult = await sdk.config.get()
|
||||
if (cfgResult.data && (cfgResult.data.share === "auto" || Flag.OPENCODE_AUTO_SHARE || args.share)) {
|
||||
const shareResult = await sdk.session.share({ path: { id: sessionID } }).catch((error) => {
|
||||
const shareResult = await sdk.session.share({ sessionID }).catch((error) => {
|
||||
if (error instanceof Error && error.message.includes("disabled")) {
|
||||
UI.println(UI.Style.TEXT_DANGER_BOLD + "! " + error.message)
|
||||
}
|
||||
|
|
@ -315,7 +312,7 @@ export const RunCommand = cmd({
|
|||
: args.title
|
||||
: undefined
|
||||
|
||||
const result = await sdk.session.create({ body: title ? { title } : {} })
|
||||
const result = await sdk.session.create(title ? { title } : {})
|
||||
return result.data?.id
|
||||
})()
|
||||
|
||||
|
|
@ -327,7 +324,7 @@ export const RunCommand = cmd({
|
|||
|
||||
const cfgResult = await sdk.config.get()
|
||||
if (cfgResult.data && (cfgResult.data.share === "auto" || Flag.OPENCODE_AUTO_SHARE || args.share)) {
|
||||
const shareResult = await sdk.session.share({ path: { id: sessionID } }).catch((error) => {
|
||||
const shareResult = await sdk.session.share({ sessionID }).catch((error) => {
|
||||
if (error instanceof Error && error.message.includes("disabled")) {
|
||||
UI.println(UI.Style.TEXT_DANGER_BOLD + "! " + error.message)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -11,7 +11,7 @@ import {
|
|||
} from "solid-js"
|
||||
import { useKeyboard } from "@opentui/solid"
|
||||
import { useKeybind } from "@tui/context/keybind"
|
||||
import type { KeybindsConfig } from "@opencode-ai/sdk"
|
||||
import type { KeybindsConfig } from "@opencode-ai/sdk/v2"
|
||||
|
||||
type Context = ReturnType<typeof init>
|
||||
const ctx = createContext<Context>()
|
||||
|
|
|
|||
|
|
@ -7,7 +7,7 @@ import { useSDK } from "../context/sdk"
|
|||
import { DialogPrompt } from "../ui/dialog-prompt"
|
||||
import { useTheme } from "../context/theme"
|
||||
import { TextAttributes } from "@opentui/core"
|
||||
import type { ProviderAuthAuthorization } from "@opencode-ai/sdk"
|
||||
import type { ProviderAuthAuthorization } from "@opencode-ai/sdk/v2"
|
||||
import { DialogModel } from "./dialog-model"
|
||||
|
||||
const PROVIDER_PRIORITY: Record<string, number> = {
|
||||
|
|
@ -64,12 +64,8 @@ export function createDialogProviderOptions() {
|
|||
const method = methods[index]
|
||||
if (method.type === "oauth") {
|
||||
const result = await sdk.client.provider.oauth.authorize({
|
||||
path: {
|
||||
id: provider.id,
|
||||
},
|
||||
body: {
|
||||
method: index,
|
||||
},
|
||||
providerID: provider.id,
|
||||
method: index,
|
||||
})
|
||||
if (result.data?.method === "code") {
|
||||
dialog.replace(() => (
|
||||
|
|
@ -111,12 +107,8 @@ function AutoMethod(props: AutoMethodProps) {
|
|||
|
||||
onMount(async () => {
|
||||
const result = await sdk.client.provider.oauth.callback({
|
||||
path: {
|
||||
id: props.providerID,
|
||||
},
|
||||
body: {
|
||||
method: props.index,
|
||||
},
|
||||
providerID: props.providerID,
|
||||
method: props.index,
|
||||
})
|
||||
if (result.error) {
|
||||
dialog.clear()
|
||||
|
|
@ -161,13 +153,9 @@ function CodeMethod(props: CodeMethodProps) {
|
|||
placeholder="Authorization code"
|
||||
onConfirm={async (value) => {
|
||||
const { error } = await sdk.client.provider.oauth.callback({
|
||||
path: {
|
||||
id: props.providerID,
|
||||
},
|
||||
body: {
|
||||
method: props.index,
|
||||
code: value,
|
||||
},
|
||||
providerID: props.providerID,
|
||||
method: props.index,
|
||||
code: value,
|
||||
})
|
||||
if (!error) {
|
||||
await sdk.client.instance.dispose()
|
||||
|
|
@ -219,10 +207,8 @@ function ApiMethod(props: ApiMethodProps) {
|
|||
onConfirm={async (value) => {
|
||||
if (!value) return
|
||||
sdk.client.auth.set({
|
||||
path: {
|
||||
id: props.providerID,
|
||||
},
|
||||
body: {
|
||||
providerID: props.providerID,
|
||||
auth: {
|
||||
type: "api",
|
||||
key: value,
|
||||
},
|
||||
|
|
|
|||
|
|
@ -74,9 +74,7 @@ export function DialogSessionList() {
|
|||
onTrigger: async (option) => {
|
||||
if (toDelete() === option.value) {
|
||||
sdk.client.session.delete({
|
||||
path: {
|
||||
id: option.value,
|
||||
},
|
||||
sessionID: option.value,
|
||||
})
|
||||
setToDelete(undefined)
|
||||
// dialog.clear()
|
||||
|
|
|
|||
|
|
@ -20,12 +20,8 @@ export function DialogSessionRename(props: DialogSessionRenameProps) {
|
|||
value={session()?.title}
|
||||
onConfirm={(value) => {
|
||||
sdk.client.session.update({
|
||||
path: {
|
||||
id: props.session,
|
||||
},
|
||||
body: {
|
||||
title: value,
|
||||
},
|
||||
sessionID: props.session,
|
||||
title: value,
|
||||
})
|
||||
dialog.clear()
|
||||
}}
|
||||
|
|
|
|||
|
|
@ -16,9 +16,7 @@ export function DialogTag(props: { onSelect?: (value: string) => void }) {
|
|||
() => [store.filter],
|
||||
async () => {
|
||||
const result = await sdk.client.find.files({
|
||||
query: {
|
||||
query: store.filter,
|
||||
},
|
||||
query: store.filter,
|
||||
})
|
||||
if (result.error) return []
|
||||
const sliced = (result.data ?? []).slice(0, 5)
|
||||
|
|
|
|||
|
|
@ -140,9 +140,7 @@ export function Autocomplete(props: {
|
|||
|
||||
// Get files from SDK
|
||||
const result = await sdk.client.find.files({
|
||||
query: {
|
||||
query: query ?? "",
|
||||
},
|
||||
query: query ?? "",
|
||||
})
|
||||
|
||||
const options: AutocompleteOption[] = []
|
||||
|
|
|
|||
|
|
@ -5,7 +5,7 @@ import { createStore, produce } from "solid-js/store"
|
|||
import { clone } from "remeda"
|
||||
import { createSimpleContext } from "../../context/helper"
|
||||
import { appendFile, writeFile } from "fs/promises"
|
||||
import type { AgentPart, FilePart, TextPart } from "@opencode-ai/sdk"
|
||||
import type { AgentPart, FilePart, TextPart } from "@opencode-ai/sdk/v2"
|
||||
|
||||
export type PromptInfo = {
|
||||
input: string
|
||||
|
|
|
|||
|
|
@ -17,7 +17,7 @@ import { useRenderer } from "@opentui/solid"
|
|||
import { Editor } from "@tui/util/editor"
|
||||
import { useExit } from "../../context/exit"
|
||||
import { Clipboard } from "../../util/clipboard"
|
||||
import type { FilePart } from "@opencode-ai/sdk"
|
||||
import type { FilePart } from "@opencode-ai/sdk/v2"
|
||||
import { TuiEvent } from "../../event"
|
||||
import { iife } from "@/util/iife"
|
||||
import { Locale } from "@/util/locale"
|
||||
|
|
@ -170,9 +170,7 @@ export function Prompt(props: PromptProps) {
|
|||
|
||||
if (store.interrupt >= 2) {
|
||||
sdk.client.session.abort({
|
||||
path: {
|
||||
id: props.sessionID,
|
||||
},
|
||||
sessionID: props.sessionID,
|
||||
})
|
||||
setStore("interrupt", 0)
|
||||
}
|
||||
|
|
@ -447,17 +445,13 @@ export function Prompt(props: PromptProps) {
|
|||
|
||||
if (store.mode === "shell") {
|
||||
sdk.client.session.shell({
|
||||
path: {
|
||||
id: sessionID,
|
||||
},
|
||||
body: {
|
||||
agent: local.agent.current().name,
|
||||
model: {
|
||||
providerID: selectedModel.providerID,
|
||||
modelID: selectedModel.modelID,
|
||||
},
|
||||
command: inputText,
|
||||
sessionID,
|
||||
agent: local.agent.current().name,
|
||||
model: {
|
||||
providerID: selectedModel.providerID,
|
||||
modelID: selectedModel.modelID,
|
||||
},
|
||||
command: inputText,
|
||||
})
|
||||
setStore("mode", "normal")
|
||||
} else if (
|
||||
|
|
@ -470,39 +464,31 @@ export function Prompt(props: PromptProps) {
|
|||
) {
|
||||
let [command, ...args] = inputText.split(" ")
|
||||
sdk.client.session.command({
|
||||
path: {
|
||||
id: sessionID,
|
||||
},
|
||||
body: {
|
||||
command: command.slice(1),
|
||||
arguments: args.join(" "),
|
||||
agent: local.agent.current().name,
|
||||
model: `${selectedModel.providerID}/${selectedModel.modelID}`,
|
||||
messageID,
|
||||
},
|
||||
sessionID,
|
||||
command: command.slice(1),
|
||||
arguments: args.join(" "),
|
||||
agent: local.agent.current().name,
|
||||
model: `${selectedModel.providerID}/${selectedModel.modelID}`,
|
||||
messageID,
|
||||
})
|
||||
} else {
|
||||
sdk.client.session.prompt({
|
||||
path: {
|
||||
id: sessionID,
|
||||
},
|
||||
body: {
|
||||
...selectedModel,
|
||||
messageID,
|
||||
agent: local.agent.current().name,
|
||||
model: selectedModel,
|
||||
parts: [
|
||||
{
|
||||
id: Identifier.ascending("part"),
|
||||
type: "text",
|
||||
text: inputText,
|
||||
},
|
||||
...nonTextParts.map((x) => ({
|
||||
id: Identifier.ascending("part"),
|
||||
...x,
|
||||
})),
|
||||
],
|
||||
},
|
||||
sessionID,
|
||||
...selectedModel,
|
||||
messageID,
|
||||
agent: local.agent.current().name,
|
||||
model: selectedModel,
|
||||
parts: [
|
||||
{
|
||||
id: Identifier.ascending("part"),
|
||||
type: "text",
|
||||
text: inputText,
|
||||
},
|
||||
...nonTextParts.map((x) => ({
|
||||
id: Identifier.ascending("part"),
|
||||
...x,
|
||||
})),
|
||||
],
|
||||
})
|
||||
}
|
||||
history.append(store.prompt)
|
||||
|
|
|
|||
|
|
@ -2,7 +2,7 @@ import { createMemo } from "solid-js"
|
|||
import { useSync } from "@tui/context/sync"
|
||||
import { Keybind } from "@/util/keybind"
|
||||
import { pipe, mapValues } from "remeda"
|
||||
import type { KeybindsConfig } from "@opencode-ai/sdk"
|
||||
import type { KeybindsConfig } from "@opencode-ai/sdk/v2"
|
||||
import type { ParsedKey, Renderable } from "@opentui/core"
|
||||
import { createStore } from "solid-js/store"
|
||||
import { useKeyboard, useRenderer } from "@opentui/solid"
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
import { createOpencodeClient, type Event } from "@opencode-ai/sdk"
|
||||
import { createOpencodeClient, type Event } from "@opencode-ai/sdk/v2"
|
||||
import { createSimpleContext } from "./helper"
|
||||
import { createGlobalEmitter } from "@solid-primitives/event-bus"
|
||||
import { batch, onCleanup, onMount } from "solid-js"
|
||||
|
|
@ -20,9 +20,12 @@ export const { use: useSDK, provider: SDKProvider } = createSimpleContext({
|
|||
onMount(async () => {
|
||||
while (true) {
|
||||
if (abort.signal.aborted) break
|
||||
const events = await sdk.event.subscribe({
|
||||
signal: abort.signal,
|
||||
})
|
||||
const events = await sdk.event.subscribe(
|
||||
{},
|
||||
{
|
||||
signal: abort.signal,
|
||||
},
|
||||
)
|
||||
let queue: Event[] = []
|
||||
let timer: Timer | undefined
|
||||
let last = 0
|
||||
|
|
|
|||
|
|
@ -15,7 +15,7 @@ import type {
|
|||
ProviderListResponse,
|
||||
ProviderAuthMethod,
|
||||
VcsInfo,
|
||||
} from "@opencode-ai/sdk"
|
||||
} from "@opencode-ai/sdk/v2"
|
||||
import { createStore, produce, reconcile } from "solid-js/store"
|
||||
import { useSDK } from "@tui/context/sdk"
|
||||
import { Binary } from "@opencode-ai/util/binary"
|
||||
|
|
@ -255,19 +255,19 @@ export const { use: useSync, provider: SyncProvider } = createSimpleContext({
|
|||
async function bootstrap() {
|
||||
// blocking
|
||||
await Promise.all([
|
||||
sdk.client.config.providers({ throwOnError: true }).then((x) => {
|
||||
sdk.client.config.providers({}, { throwOnError: true }).then((x) => {
|
||||
batch(() => {
|
||||
setStore("provider", x.data!.providers)
|
||||
setStore("provider_default", x.data!.default)
|
||||
})
|
||||
}),
|
||||
sdk.client.provider.list({ throwOnError: true }).then((x) => {
|
||||
sdk.client.provider.list({}, { throwOnError: true }).then((x) => {
|
||||
batch(() => {
|
||||
setStore("provider_next", x.data!)
|
||||
})
|
||||
}),
|
||||
sdk.client.app.agents({ throwOnError: true }).then((x) => setStore("agent", x.data ?? [])),
|
||||
sdk.client.config.get({ throwOnError: true }).then((x) => setStore("config", x.data!)),
|
||||
sdk.client.app.agents({}, { throwOnError: true }).then((x) => setStore("agent", x.data ?? [])),
|
||||
sdk.client.config.get({}, { throwOnError: true }).then((x) => setStore("config", x.data!)),
|
||||
])
|
||||
.then(() => {
|
||||
if (store.status !== "complete") setStore("status", "partial")
|
||||
|
|
@ -333,10 +333,10 @@ export const { use: useSync, provider: SyncProvider } = createSimpleContext({
|
|||
async sync(sessionID: string) {
|
||||
if (fullSyncedSessions.has(sessionID)) return
|
||||
const [session, messages, todo, diff] = await Promise.all([
|
||||
sdk.client.session.get({ path: { id: sessionID }, throwOnError: true }),
|
||||
sdk.client.session.messages({ path: { id: sessionID }, query: { limit: 100 } }),
|
||||
sdk.client.session.todo({ path: { id: sessionID } }),
|
||||
sdk.client.session.diff({ path: { id: sessionID } }),
|
||||
sdk.client.session.get({ sessionID }, { throwOnError: true }),
|
||||
sdk.client.session.messages({ sessionID, limit: 100 }),
|
||||
sdk.client.session.todo({ sessionID }),
|
||||
sdk.client.session.diff({ sessionID }),
|
||||
])
|
||||
setStore(
|
||||
produce((draft) => {
|
||||
|
|
|
|||
|
|
@ -29,12 +29,8 @@ export function DialogMessage(props: {
|
|||
if (!msg) return
|
||||
|
||||
sdk.client.session.revert({
|
||||
path: {
|
||||
id: props.sessionID,
|
||||
},
|
||||
body: {
|
||||
messageID: msg.id,
|
||||
},
|
||||
sessionID: props.sessionID,
|
||||
messageID: msg.id,
|
||||
})
|
||||
|
||||
if (props.setPrompt) {
|
||||
|
|
@ -81,12 +77,8 @@ export function DialogMessage(props: {
|
|||
description: "create a new session",
|
||||
onSelect: async (dialog) => {
|
||||
const result = await sdk.client.session.fork({
|
||||
path: {
|
||||
id: props.sessionID,
|
||||
},
|
||||
body: {
|
||||
messageID: props.messageID,
|
||||
},
|
||||
sessionID: props.sessionID,
|
||||
messageID: props.messageID,
|
||||
})
|
||||
route.navigate({
|
||||
sessionID: result.data!.id,
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
import { createMemo, onMount } from "solid-js"
|
||||
import { useSync } from "@tui/context/sync"
|
||||
import { DialogSelect, type DialogSelectOption } from "@tui/ui/dialog-select"
|
||||
import type { TextPart } from "@opencode-ai/sdk"
|
||||
import type { TextPart } from "@opencode-ai/sdk/v2"
|
||||
import { Locale } from "@/util/locale"
|
||||
import { DialogMessage } from "./dialog-message"
|
||||
import { useDialog } from "../../ui/dialog"
|
||||
|
|
|
|||
|
|
@ -4,7 +4,7 @@ import { useSync } from "@tui/context/sync"
|
|||
import { pipe, sumBy } from "remeda"
|
||||
import { useTheme } from "@tui/context/theme"
|
||||
import { SplitBorder, EmptyBorder } from "@tui/component/border"
|
||||
import type { AssistantMessage, Session } from "@opencode-ai/sdk"
|
||||
import type { AssistantMessage, Session } from "@opencode-ai/sdk/v2"
|
||||
import { useDirectory } from "../../context/directory"
|
||||
import { useKeybind } from "../../context/keybind"
|
||||
|
||||
|
|
|
|||
|
|
@ -25,7 +25,7 @@ import {
|
|||
type ScrollAcceleration,
|
||||
} from "@opentui/core"
|
||||
import { Prompt, type PromptRef } from "@tui/component/prompt"
|
||||
import type { AssistantMessage, Part, ToolPart, UserMessage, TextPart, ReasoningPart } from "@opencode-ai/sdk"
|
||||
import type { AssistantMessage, Part, ToolPart, UserMessage, TextPart, ReasoningPart } from "@opencode-ai/sdk/v2"
|
||||
import { useLocal } from "@tui/context/local"
|
||||
import { Locale } from "@/util/locale"
|
||||
import type { Tool } from "@/tool/tool"
|
||||
|
|
@ -150,7 +150,8 @@ export function Session() {
|
|||
.then(() => {
|
||||
if (scroll) scroll.scrollBy(100_000)
|
||||
})
|
||||
.catch(() => {
|
||||
.catch((e) => {
|
||||
console.error(e)
|
||||
toast.show({
|
||||
message: `Session not found: ${route.sessionID}`,
|
||||
variant: "error",
|
||||
|
|
@ -202,14 +203,10 @@ export function Session() {
|
|||
return
|
||||
})
|
||||
if (response) {
|
||||
sdk.client.postSessionIdPermissionsPermissionId({
|
||||
path: {
|
||||
permissionID: first.id,
|
||||
id: route.sessionID,
|
||||
},
|
||||
body: {
|
||||
response: response,
|
||||
},
|
||||
sdk.client.permission.respond({
|
||||
permissionID: first.id,
|
||||
sessionID: route.sessionID,
|
||||
response: response,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
|
@ -254,9 +251,7 @@ export function Session() {
|
|||
onSelect: async (dialog: any) => {
|
||||
await sdk.client.session
|
||||
.share({
|
||||
path: {
|
||||
id: route.sessionID,
|
||||
},
|
||||
sessionID: route.sessionID,
|
||||
})
|
||||
.then((res) =>
|
||||
Clipboard.copy(res.data!.share!.url).catch(() =>
|
||||
|
|
@ -314,13 +309,9 @@ export function Session() {
|
|||
return
|
||||
}
|
||||
sdk.client.session.summarize({
|
||||
path: {
|
||||
id: route.sessionID,
|
||||
},
|
||||
body: {
|
||||
modelID: selectedModel.modelID,
|
||||
providerID: selectedModel.providerID,
|
||||
},
|
||||
sessionID: route.sessionID,
|
||||
modelID: selectedModel.modelID,
|
||||
providerID: selectedModel.providerID,
|
||||
})
|
||||
dialog.clear()
|
||||
},
|
||||
|
|
@ -333,9 +324,7 @@ export function Session() {
|
|||
category: "Session",
|
||||
onSelect: (dialog) => {
|
||||
sdk.client.session.unshare({
|
||||
path: {
|
||||
id: route.sessionID,
|
||||
},
|
||||
sessionID: route.sessionID,
|
||||
})
|
||||
dialog.clear()
|
||||
},
|
||||
|
|
@ -347,18 +336,14 @@ export function Session() {
|
|||
category: "Session",
|
||||
onSelect: async (dialog) => {
|
||||
const status = sync.data.session_status[route.sessionID]
|
||||
if (status?.type !== "idle") await sdk.client.session.abort({ path: { id: route.sessionID } }).catch(() => {})
|
||||
if (status?.type !== "idle") await sdk.client.session.abort({ sessionID: route.sessionID }).catch(() => {})
|
||||
const revert = session().revert?.messageID
|
||||
const message = messages().findLast((x) => (!revert || x.id < revert) && x.role === "user")
|
||||
if (!message) return
|
||||
sdk.client.session
|
||||
.revert({
|
||||
path: {
|
||||
id: route.sessionID,
|
||||
},
|
||||
body: {
|
||||
messageID: message.id,
|
||||
},
|
||||
sessionID: route.sessionID,
|
||||
messageID: message.id,
|
||||
})
|
||||
.then(() => {
|
||||
toBottom()
|
||||
|
|
@ -392,20 +377,14 @@ export function Session() {
|
|||
const message = messages().find((x) => x.role === "user" && x.id > messageID)
|
||||
if (!message) {
|
||||
sdk.client.session.unrevert({
|
||||
path: {
|
||||
id: route.sessionID,
|
||||
},
|
||||
sessionID: route.sessionID,
|
||||
})
|
||||
prompt.set({ input: "", parts: [] })
|
||||
return
|
||||
}
|
||||
sdk.client.session.revert({
|
||||
path: {
|
||||
id: route.sessionID,
|
||||
},
|
||||
body: {
|
||||
messageID: message.id,
|
||||
},
|
||||
sessionID: route.sessionID,
|
||||
messageID: message.id,
|
||||
})
|
||||
},
|
||||
},
|
||||
|
|
|
|||
|
|
@ -4,7 +4,7 @@ import { createStore } from "solid-js/store"
|
|||
import { useTheme } from "../../context/theme"
|
||||
import { Locale } from "@/util/locale"
|
||||
import path from "path"
|
||||
import type { AssistantMessage } from "@opencode-ai/sdk"
|
||||
import type { AssistantMessage } from "@opencode-ai/sdk/v2"
|
||||
import { Global } from "@/global"
|
||||
import { Installation } from "@/installation"
|
||||
import { useKeybind } from "../../context/keybind"
|
||||
|
|
|
|||
|
|
@ -61,10 +61,14 @@ export namespace Plugin {
|
|||
for (const hook of await state().then((x) => x.hooks)) {
|
||||
const fn = hook[name]
|
||||
if (!fn) continue
|
||||
// @ts-expect-error if you feel adventurous, please fix the typing, make sure to bump the try-counter if you
|
||||
// give up.
|
||||
// try-counter: 2
|
||||
await fn(input, output)
|
||||
try {
|
||||
// @ts-expect-error if you feel adventurous, please fix the typing, make sure to bump the try-counter if you
|
||||
// give up.
|
||||
// try-counter: 2
|
||||
await fn(input, output)
|
||||
} catch (e) {
|
||||
log.error("failed to trigger hook", { name, error: e })
|
||||
}
|
||||
}
|
||||
return output
|
||||
}
|
||||
|
|
|
|||
|
|
@ -209,7 +209,7 @@ export namespace Server {
|
|||
},
|
||||
)
|
||||
.get(
|
||||
"/pty/:id",
|
||||
"/pty/:ptyID",
|
||||
describeRoute({
|
||||
description: "Get PTY session info",
|
||||
operationId: "pty.get",
|
||||
|
|
@ -225,9 +225,9 @@ export namespace Server {
|
|||
...errors(404),
|
||||
},
|
||||
}),
|
||||
validator("param", z.object({ id: z.string() })),
|
||||
validator("param", z.object({ ptyID: z.string() })),
|
||||
async (c) => {
|
||||
const info = Pty.get(c.req.valid("param").id)
|
||||
const info = Pty.get(c.req.valid("param").ptyID)
|
||||
if (!info) {
|
||||
throw new Storage.NotFoundError({ message: "Session not found" })
|
||||
}
|
||||
|
|
@ -235,7 +235,7 @@ export namespace Server {
|
|||
},
|
||||
)
|
||||
.put(
|
||||
"/pty/:id",
|
||||
"/pty/:ptyID",
|
||||
describeRoute({
|
||||
description: "Update PTY session",
|
||||
operationId: "pty.update",
|
||||
|
|
@ -251,15 +251,15 @@ export namespace Server {
|
|||
...errors(400),
|
||||
},
|
||||
}),
|
||||
validator("param", z.object({ id: z.string() })),
|
||||
validator("param", z.object({ ptyID: z.string() })),
|
||||
validator("json", Pty.UpdateInput),
|
||||
async (c) => {
|
||||
const info = await Pty.update(c.req.valid("param").id, c.req.valid("json"))
|
||||
const info = await Pty.update(c.req.valid("param").ptyID, c.req.valid("json"))
|
||||
return c.json(info)
|
||||
},
|
||||
)
|
||||
.delete(
|
||||
"/pty/:id",
|
||||
"/pty/:ptyID",
|
||||
describeRoute({
|
||||
description: "Remove a PTY session",
|
||||
operationId: "pty.remove",
|
||||
|
|
@ -275,14 +275,14 @@ export namespace Server {
|
|||
...errors(404),
|
||||
},
|
||||
}),
|
||||
validator("param", z.object({ id: z.string() })),
|
||||
validator("param", z.object({ ptyID: z.string() })),
|
||||
async (c) => {
|
||||
await Pty.remove(c.req.valid("param").id)
|
||||
await Pty.remove(c.req.valid("param").ptyID)
|
||||
return c.json(true)
|
||||
},
|
||||
)
|
||||
.get(
|
||||
"/pty/:id/connect",
|
||||
"/pty/:ptyID/connect",
|
||||
describeRoute({
|
||||
description: "Connect to a PTY session",
|
||||
operationId: "pty.connect",
|
||||
|
|
@ -298,9 +298,9 @@ export namespace Server {
|
|||
...errors(404),
|
||||
},
|
||||
}),
|
||||
validator("param", z.object({ id: z.string() })),
|
||||
validator("param", z.object({ ptyID: z.string() })),
|
||||
upgradeWebSocket((c) => {
|
||||
const id = c.req.param("id")
|
||||
const id = c.req.param("ptyID")
|
||||
let handler: ReturnType<typeof Pty.connect>
|
||||
if (!Pty.get(id)) throw new Error("Session not found")
|
||||
return {
|
||||
|
|
@ -557,7 +557,7 @@ export namespace Server {
|
|||
},
|
||||
)
|
||||
.get(
|
||||
"/session/:id",
|
||||
"/session/:sessionID",
|
||||
describeRoute({
|
||||
description: "Get session",
|
||||
operationId: "session.get",
|
||||
|
|
@ -576,17 +576,18 @@ export namespace Server {
|
|||
validator(
|
||||
"param",
|
||||
z.object({
|
||||
id: Session.get.schema,
|
||||
sessionID: Session.get.schema,
|
||||
}),
|
||||
),
|
||||
async (c) => {
|
||||
const sessionID = c.req.valid("param").id
|
||||
const sessionID = c.req.valid("param").sessionID
|
||||
log.info("SEARCH", { url: c.req.url })
|
||||
const session = await Session.get(sessionID)
|
||||
return c.json(session)
|
||||
},
|
||||
)
|
||||
.get(
|
||||
"/session/:id/children",
|
||||
"/session/:sessionID/children",
|
||||
describeRoute({
|
||||
description: "Get a session's children",
|
||||
operationId: "session.children",
|
||||
|
|
@ -605,17 +606,17 @@ export namespace Server {
|
|||
validator(
|
||||
"param",
|
||||
z.object({
|
||||
id: Session.children.schema,
|
||||
sessionID: Session.children.schema,
|
||||
}),
|
||||
),
|
||||
async (c) => {
|
||||
const sessionID = c.req.valid("param").id
|
||||
const sessionID = c.req.valid("param").sessionID
|
||||
const session = await Session.children(sessionID)
|
||||
return c.json(session)
|
||||
},
|
||||
)
|
||||
.get(
|
||||
"/session/:id/todo",
|
||||
"/session/:sessionID/todo",
|
||||
describeRoute({
|
||||
description: "Get the todo list for a session",
|
||||
operationId: "session.todo",
|
||||
|
|
@ -634,11 +635,11 @@ export namespace Server {
|
|||
validator(
|
||||
"param",
|
||||
z.object({
|
||||
id: z.string().meta({ description: "Session ID" }),
|
||||
sessionID: z.string().meta({ description: "Session ID" }),
|
||||
}),
|
||||
),
|
||||
async (c) => {
|
||||
const sessionID = c.req.valid("param").id
|
||||
const sessionID = c.req.valid("param").sessionID
|
||||
const todos = await Todo.get(sessionID)
|
||||
return c.json(todos)
|
||||
},
|
||||
|
|
@ -668,7 +669,7 @@ export namespace Server {
|
|||
},
|
||||
)
|
||||
.delete(
|
||||
"/session/:id",
|
||||
"/session/:sessionID",
|
||||
describeRoute({
|
||||
description: "Delete a session and all its data",
|
||||
operationId: "session.delete",
|
||||
|
|
@ -687,11 +688,11 @@ export namespace Server {
|
|||
validator(
|
||||
"param",
|
||||
z.object({
|
||||
id: Session.remove.schema,
|
||||
sessionID: Session.remove.schema,
|
||||
}),
|
||||
),
|
||||
async (c) => {
|
||||
const sessionID = c.req.valid("param").id
|
||||
const sessionID = c.req.valid("param").sessionID
|
||||
await Session.remove(sessionID)
|
||||
await Bus.publish(TuiEvent.CommandExecute, {
|
||||
command: "session.list",
|
||||
|
|
@ -700,7 +701,7 @@ export namespace Server {
|
|||
},
|
||||
)
|
||||
.patch(
|
||||
"/session/:id",
|
||||
"/session/:sessionID",
|
||||
describeRoute({
|
||||
description: "Update session properties",
|
||||
operationId: "session.update",
|
||||
|
|
@ -719,7 +720,7 @@ export namespace Server {
|
|||
validator(
|
||||
"param",
|
||||
z.object({
|
||||
id: z.string(),
|
||||
sessionID: z.string(),
|
||||
}),
|
||||
),
|
||||
validator(
|
||||
|
|
@ -729,7 +730,7 @@ export namespace Server {
|
|||
}),
|
||||
),
|
||||
async (c) => {
|
||||
const sessionID = c.req.valid("param").id
|
||||
const sessionID = c.req.valid("param").sessionID
|
||||
const updates = c.req.valid("json")
|
||||
|
||||
const updatedSession = await Session.update(sessionID, (session) => {
|
||||
|
|
@ -742,7 +743,7 @@ export namespace Server {
|
|||
},
|
||||
)
|
||||
.post(
|
||||
"/session/:id/init",
|
||||
"/session/:sessionID/init",
|
||||
describeRoute({
|
||||
description: "Analyze the app and create an AGENTS.md file",
|
||||
operationId: "session.init",
|
||||
|
|
@ -761,19 +762,19 @@ export namespace Server {
|
|||
validator(
|
||||
"param",
|
||||
z.object({
|
||||
id: z.string().meta({ description: "Session ID" }),
|
||||
sessionID: z.string().meta({ description: "Session ID" }),
|
||||
}),
|
||||
),
|
||||
validator("json", Session.initialize.schema.omit({ sessionID: true })),
|
||||
async (c) => {
|
||||
const sessionID = c.req.valid("param").id
|
||||
const sessionID = c.req.valid("param").sessionID
|
||||
const body = c.req.valid("json")
|
||||
await Session.initialize({ ...body, sessionID })
|
||||
return c.json(true)
|
||||
},
|
||||
)
|
||||
.post(
|
||||
"/session/:id/fork",
|
||||
"/session/:sessionID/fork",
|
||||
describeRoute({
|
||||
description: "Fork an existing session at a specific message",
|
||||
operationId: "session.fork",
|
||||
|
|
@ -791,19 +792,19 @@ export namespace Server {
|
|||
validator(
|
||||
"param",
|
||||
z.object({
|
||||
id: Session.fork.schema.shape.sessionID,
|
||||
sessionID: Session.fork.schema.shape.sessionID,
|
||||
}),
|
||||
),
|
||||
validator("json", Session.fork.schema.omit({ sessionID: true })),
|
||||
async (c) => {
|
||||
const sessionID = c.req.valid("param").id
|
||||
const sessionID = c.req.valid("param").sessionID
|
||||
const body = c.req.valid("json")
|
||||
const result = await Session.fork({ ...body, sessionID })
|
||||
return c.json(result)
|
||||
},
|
||||
)
|
||||
.post(
|
||||
"/session/:id/abort",
|
||||
"/session/:sessionID/abort",
|
||||
describeRoute({
|
||||
description: "Abort a session",
|
||||
operationId: "session.abort",
|
||||
|
|
@ -822,16 +823,16 @@ export namespace Server {
|
|||
validator(
|
||||
"param",
|
||||
z.object({
|
||||
id: z.string(),
|
||||
sessionID: z.string(),
|
||||
}),
|
||||
),
|
||||
async (c) => {
|
||||
SessionPrompt.cancel(c.req.valid("param").id)
|
||||
SessionPrompt.cancel(c.req.valid("param").sessionID)
|
||||
return c.json(true)
|
||||
},
|
||||
)
|
||||
.post(
|
||||
"/session/:id/share",
|
||||
"/session/:sessionID/share",
|
||||
describeRoute({
|
||||
description: "Share a session",
|
||||
operationId: "session.share",
|
||||
|
|
@ -850,18 +851,18 @@ export namespace Server {
|
|||
validator(
|
||||
"param",
|
||||
z.object({
|
||||
id: z.string(),
|
||||
sessionID: z.string(),
|
||||
}),
|
||||
),
|
||||
async (c) => {
|
||||
const id = c.req.valid("param").id
|
||||
await Session.share(id)
|
||||
const session = await Session.get(id)
|
||||
const sessionID = c.req.valid("param").sessionID
|
||||
await Session.share(sessionID)
|
||||
const session = await Session.get(sessionID)
|
||||
return c.json(session)
|
||||
},
|
||||
)
|
||||
.get(
|
||||
"/session/:id/diff",
|
||||
"/session/:sessionID/diff",
|
||||
describeRoute({
|
||||
description: "Get the diff that resulted from this user message",
|
||||
operationId: "session.diff",
|
||||
|
|
@ -879,7 +880,7 @@ export namespace Server {
|
|||
validator(
|
||||
"param",
|
||||
z.object({
|
||||
id: SessionSummary.diff.schema.shape.sessionID,
|
||||
sessionID: SessionSummary.diff.schema.shape.sessionID,
|
||||
}),
|
||||
),
|
||||
validator(
|
||||
|
|
@ -892,14 +893,14 @@ export namespace Server {
|
|||
const query = c.req.valid("query")
|
||||
const params = c.req.valid("param")
|
||||
const result = await SessionSummary.diff({
|
||||
sessionID: params.id,
|
||||
sessionID: params.sessionID,
|
||||
messageID: query.messageID,
|
||||
})
|
||||
return c.json(result)
|
||||
},
|
||||
)
|
||||
.delete(
|
||||
"/session/:id/share",
|
||||
"/session/:sessionID/share",
|
||||
describeRoute({
|
||||
description: "Unshare the session",
|
||||
operationId: "session.unshare",
|
||||
|
|
@ -918,18 +919,18 @@ export namespace Server {
|
|||
validator(
|
||||
"param",
|
||||
z.object({
|
||||
id: Session.unshare.schema,
|
||||
sessionID: Session.unshare.schema,
|
||||
}),
|
||||
),
|
||||
async (c) => {
|
||||
const id = c.req.valid("param").id
|
||||
await Session.unshare(id)
|
||||
const session = await Session.get(id)
|
||||
const sessionID = c.req.valid("param").sessionID
|
||||
await Session.unshare(sessionID)
|
||||
const session = await Session.get(sessionID)
|
||||
return c.json(session)
|
||||
},
|
||||
)
|
||||
.post(
|
||||
"/session/:id/summarize",
|
||||
"/session/:sessionID/summarize",
|
||||
describeRoute({
|
||||
description: "Summarize the session",
|
||||
operationId: "session.summarize",
|
||||
|
|
@ -948,7 +949,7 @@ export namespace Server {
|
|||
validator(
|
||||
"param",
|
||||
z.object({
|
||||
id: z.string().meta({ description: "Session ID" }),
|
||||
sessionID: z.string().meta({ description: "Session ID" }),
|
||||
}),
|
||||
),
|
||||
validator(
|
||||
|
|
@ -959,9 +960,9 @@ export namespace Server {
|
|||
}),
|
||||
),
|
||||
async (c) => {
|
||||
const id = c.req.valid("param").id
|
||||
const sessionID = c.req.valid("param").sessionID
|
||||
const body = c.req.valid("json")
|
||||
const msgs = await Session.messages({ sessionID: id })
|
||||
const msgs = await Session.messages({ sessionID })
|
||||
let currentAgent = "build"
|
||||
for (let i = msgs.length - 1; i >= 0; i--) {
|
||||
const info = msgs[i].info
|
||||
|
|
@ -971,7 +972,7 @@ export namespace Server {
|
|||
}
|
||||
}
|
||||
await SessionCompaction.create({
|
||||
sessionID: id,
|
||||
sessionID,
|
||||
agent: currentAgent,
|
||||
model: {
|
||||
providerID: body.providerID,
|
||||
|
|
@ -979,12 +980,12 @@ export namespace Server {
|
|||
},
|
||||
auto: false,
|
||||
})
|
||||
await SessionPrompt.loop(id)
|
||||
await SessionPrompt.loop(sessionID)
|
||||
return c.json(true)
|
||||
},
|
||||
)
|
||||
.get(
|
||||
"/session/:id/message",
|
||||
"/session/:sessionID/message",
|
||||
describeRoute({
|
||||
description: "List messages for a session",
|
||||
operationId: "session.messages",
|
||||
|
|
@ -1003,7 +1004,7 @@ export namespace Server {
|
|||
validator(
|
||||
"param",
|
||||
z.object({
|
||||
id: z.string().meta({ description: "Session ID" }),
|
||||
sessionID: z.string().meta({ description: "Session ID" }),
|
||||
}),
|
||||
),
|
||||
validator(
|
||||
|
|
@ -1015,14 +1016,14 @@ export namespace Server {
|
|||
async (c) => {
|
||||
const query = c.req.valid("query")
|
||||
const messages = await Session.messages({
|
||||
sessionID: c.req.valid("param").id,
|
||||
sessionID: c.req.valid("param").sessionID,
|
||||
limit: query.limit,
|
||||
})
|
||||
return c.json(messages)
|
||||
},
|
||||
)
|
||||
.get(
|
||||
"/session/:id/diff",
|
||||
"/session/:sessionID/diff",
|
||||
describeRoute({
|
||||
description: "Get the diff for this session",
|
||||
operationId: "session.diff",
|
||||
|
|
@ -1041,16 +1042,16 @@ export namespace Server {
|
|||
validator(
|
||||
"param",
|
||||
z.object({
|
||||
id: z.string().meta({ description: "Session ID" }),
|
||||
sessionID: z.string().meta({ description: "Session ID" }),
|
||||
}),
|
||||
),
|
||||
async (c) => {
|
||||
const diff = await Session.diff(c.req.valid("param").id)
|
||||
const diff = await Session.diff(c.req.valid("param").sessionID)
|
||||
return c.json(diff)
|
||||
},
|
||||
)
|
||||
.get(
|
||||
"/session/:id/message/:messageID",
|
||||
"/session/:sessionID/message/:messageID",
|
||||
describeRoute({
|
||||
description: "Get a message from a session",
|
||||
operationId: "session.message",
|
||||
|
|
@ -1074,21 +1075,21 @@ export namespace Server {
|
|||
validator(
|
||||
"param",
|
||||
z.object({
|
||||
id: z.string().meta({ description: "Session ID" }),
|
||||
sessionID: z.string().meta({ description: "Session ID" }),
|
||||
messageID: z.string().meta({ description: "Message ID" }),
|
||||
}),
|
||||
),
|
||||
async (c) => {
|
||||
const params = c.req.valid("param")
|
||||
const message = await MessageV2.get({
|
||||
sessionID: params.id,
|
||||
sessionID: params.sessionID,
|
||||
messageID: params.messageID,
|
||||
})
|
||||
return c.json(message)
|
||||
},
|
||||
)
|
||||
.post(
|
||||
"/session/:id/message",
|
||||
"/session/:sessionID/message",
|
||||
describeRoute({
|
||||
description: "Create and send a new message to a session",
|
||||
operationId: "session.prompt",
|
||||
|
|
@ -1112,7 +1113,7 @@ export namespace Server {
|
|||
validator(
|
||||
"param",
|
||||
z.object({
|
||||
id: z.string().meta({ description: "Session ID" }),
|
||||
sessionID: z.string().meta({ description: "Session ID" }),
|
||||
}),
|
||||
),
|
||||
validator("json", SessionPrompt.PromptInput.omit({ sessionID: true })),
|
||||
|
|
@ -1120,7 +1121,7 @@ export namespace Server {
|
|||
c.status(200)
|
||||
c.header("Content-Type", "application/json")
|
||||
return stream(c, async (stream) => {
|
||||
const sessionID = c.req.valid("param").id
|
||||
const sessionID = c.req.valid("param").sessionID
|
||||
const body = c.req.valid("json")
|
||||
const msg = await SessionPrompt.prompt({ ...body, sessionID })
|
||||
stream.write(JSON.stringify(msg))
|
||||
|
|
@ -1128,7 +1129,7 @@ export namespace Server {
|
|||
},
|
||||
)
|
||||
.post(
|
||||
"/session/:id/prompt_async",
|
||||
"/session/:sessionID/prompt_async",
|
||||
describeRoute({
|
||||
description: "Create and send a new message to a session, start if needed and return immediately",
|
||||
operationId: "session.prompt_async",
|
||||
|
|
@ -1142,7 +1143,7 @@ export namespace Server {
|
|||
validator(
|
||||
"param",
|
||||
z.object({
|
||||
id: z.string().meta({ description: "Session ID" }),
|
||||
sessionID: z.string().meta({ description: "Session ID" }),
|
||||
}),
|
||||
),
|
||||
validator("json", SessionPrompt.PromptInput.omit({ sessionID: true })),
|
||||
|
|
@ -1150,14 +1151,14 @@ export namespace Server {
|
|||
c.status(204)
|
||||
c.header("Content-Type", "application/json")
|
||||
return stream(c, async () => {
|
||||
const sessionID = c.req.valid("param").id
|
||||
const sessionID = c.req.valid("param").sessionID
|
||||
const body = c.req.valid("json")
|
||||
SessionPrompt.prompt({ ...body, sessionID })
|
||||
})
|
||||
},
|
||||
)
|
||||
.post(
|
||||
"/session/:id/command",
|
||||
"/session/:sessionID/command",
|
||||
describeRoute({
|
||||
description: "Send a new command to a session",
|
||||
operationId: "session.command",
|
||||
|
|
@ -1181,19 +1182,19 @@ export namespace Server {
|
|||
validator(
|
||||
"param",
|
||||
z.object({
|
||||
id: z.string().meta({ description: "Session ID" }),
|
||||
sessionID: z.string().meta({ description: "Session ID" }),
|
||||
}),
|
||||
),
|
||||
validator("json", SessionPrompt.CommandInput.omit({ sessionID: true })),
|
||||
async (c) => {
|
||||
const sessionID = c.req.valid("param").id
|
||||
const sessionID = c.req.valid("param").sessionID
|
||||
const body = c.req.valid("json")
|
||||
const msg = await SessionPrompt.command({ ...body, sessionID })
|
||||
return c.json(msg)
|
||||
},
|
||||
)
|
||||
.post(
|
||||
"/session/:id/shell",
|
||||
"/session/:sessionID/shell",
|
||||
describeRoute({
|
||||
description: "Run a shell command",
|
||||
operationId: "session.shell",
|
||||
|
|
@ -1212,19 +1213,19 @@ export namespace Server {
|
|||
validator(
|
||||
"param",
|
||||
z.object({
|
||||
id: z.string().meta({ description: "Session ID" }),
|
||||
sessionID: z.string().meta({ description: "Session ID" }),
|
||||
}),
|
||||
),
|
||||
validator("json", SessionPrompt.ShellInput.omit({ sessionID: true })),
|
||||
async (c) => {
|
||||
const sessionID = c.req.valid("param").id
|
||||
const sessionID = c.req.valid("param").sessionID
|
||||
const body = c.req.valid("json")
|
||||
const msg = await SessionPrompt.shell({ ...body, sessionID })
|
||||
return c.json(msg)
|
||||
},
|
||||
)
|
||||
.post(
|
||||
"/session/:id/revert",
|
||||
"/session/:sessionID/revert",
|
||||
describeRoute({
|
||||
description: "Revert a message",
|
||||
operationId: "session.revert",
|
||||
|
|
@ -1243,22 +1244,22 @@ export namespace Server {
|
|||
validator(
|
||||
"param",
|
||||
z.object({
|
||||
id: z.string(),
|
||||
sessionID: z.string(),
|
||||
}),
|
||||
),
|
||||
validator("json", SessionRevert.RevertInput.omit({ sessionID: true })),
|
||||
async (c) => {
|
||||
const id = c.req.valid("param").id
|
||||
const sessionID = c.req.valid("param").sessionID
|
||||
log.info("revert", c.req.valid("json"))
|
||||
const session = await SessionRevert.revert({
|
||||
sessionID: id,
|
||||
sessionID,
|
||||
...c.req.valid("json"),
|
||||
})
|
||||
return c.json(session)
|
||||
},
|
||||
)
|
||||
.post(
|
||||
"/session/:id/unrevert",
|
||||
"/session/:sessionID/unrevert",
|
||||
describeRoute({
|
||||
description: "Restore all reverted messages",
|
||||
operationId: "session.unrevert",
|
||||
|
|
@ -1277,19 +1278,20 @@ export namespace Server {
|
|||
validator(
|
||||
"param",
|
||||
z.object({
|
||||
id: z.string(),
|
||||
sessionID: z.string(),
|
||||
}),
|
||||
),
|
||||
async (c) => {
|
||||
const id = c.req.valid("param").id
|
||||
const session = await SessionRevert.unrevert({ sessionID: id })
|
||||
const sessionID = c.req.valid("param").sessionID
|
||||
const session = await SessionRevert.unrevert({ sessionID })
|
||||
return c.json(session)
|
||||
},
|
||||
)
|
||||
.post(
|
||||
"/session/:id/permissions/:permissionID",
|
||||
"/session/:sessionID/permissions/:permissionID",
|
||||
describeRoute({
|
||||
description: "Respond to a permission request",
|
||||
operationId: "permission.respond",
|
||||
responses: {
|
||||
200: {
|
||||
description: "Permission processed successfully",
|
||||
|
|
@ -1305,17 +1307,17 @@ export namespace Server {
|
|||
validator(
|
||||
"param",
|
||||
z.object({
|
||||
id: z.string(),
|
||||
sessionID: z.string(),
|
||||
permissionID: z.string(),
|
||||
}),
|
||||
),
|
||||
validator("json", z.object({ response: Permission.Response })),
|
||||
async (c) => {
|
||||
const params = c.req.valid("param")
|
||||
const id = params.id
|
||||
const sessionID = params.sessionID
|
||||
const permissionID = params.permissionID
|
||||
Permission.respond({
|
||||
sessionID: id,
|
||||
sessionID,
|
||||
permissionID,
|
||||
response: c.req.valid("json").response,
|
||||
})
|
||||
|
|
@ -1429,7 +1431,7 @@ export namespace Server {
|
|||
},
|
||||
)
|
||||
.post(
|
||||
"/provider/:id/oauth/authorize",
|
||||
"/provider/:providerID/oauth/authorize",
|
||||
describeRoute({
|
||||
description: "Authorize a provider using OAuth",
|
||||
operationId: "provider.oauth.authorize",
|
||||
|
|
@ -1448,7 +1450,7 @@ export namespace Server {
|
|||
validator(
|
||||
"param",
|
||||
z.object({
|
||||
id: z.string().meta({ description: "Provider ID" }),
|
||||
providerID: z.string().meta({ description: "Provider ID" }),
|
||||
}),
|
||||
),
|
||||
validator(
|
||||
|
|
@ -1458,17 +1460,17 @@ export namespace Server {
|
|||
}),
|
||||
),
|
||||
async (c) => {
|
||||
const id = c.req.valid("param").id
|
||||
const providerID = c.req.valid("param").providerID
|
||||
const { method } = c.req.valid("json")
|
||||
const result = await ProviderAuth.authorize({
|
||||
providerID: id,
|
||||
providerID,
|
||||
method,
|
||||
})
|
||||
return c.json(result)
|
||||
},
|
||||
)
|
||||
.post(
|
||||
"/provider/:id/oauth/callback",
|
||||
"/provider/:providerID/oauth/callback",
|
||||
describeRoute({
|
||||
description: "Handle OAuth callback for a provider",
|
||||
operationId: "provider.oauth.callback",
|
||||
|
|
@ -1487,7 +1489,7 @@ export namespace Server {
|
|||
validator(
|
||||
"param",
|
||||
z.object({
|
||||
id: z.string().meta({ description: "Provider ID" }),
|
||||
providerID: z.string().meta({ description: "Provider ID" }),
|
||||
}),
|
||||
),
|
||||
validator(
|
||||
|
|
@ -1498,10 +1500,10 @@ export namespace Server {
|
|||
}),
|
||||
),
|
||||
async (c) => {
|
||||
const id = c.req.valid("param").id
|
||||
const providerID = c.req.valid("param").providerID
|
||||
const { method, code } = c.req.valid("json")
|
||||
await ProviderAuth.callback({
|
||||
providerID: id,
|
||||
providerID,
|
||||
method,
|
||||
code,
|
||||
})
|
||||
|
|
@ -2215,7 +2217,7 @@ export namespace Server {
|
|||
)
|
||||
.route("/tui/control", TuiRoute)
|
||||
.put(
|
||||
"/auth/:id",
|
||||
"/auth/:providerID",
|
||||
describeRoute({
|
||||
description: "Set authentication credentials",
|
||||
operationId: "auth.set",
|
||||
|
|
@ -2234,14 +2236,14 @@ export namespace Server {
|
|||
validator(
|
||||
"param",
|
||||
z.object({
|
||||
id: z.string(),
|
||||
providerID: z.string(),
|
||||
}),
|
||||
),
|
||||
validator("json", Auth.Info),
|
||||
async (c) => {
|
||||
const id = c.req.valid("param").id
|
||||
const providerID = c.req.valid("param").providerID
|
||||
const info = c.req.valid("json")
|
||||
await Auth.set(id, info)
|
||||
await Auth.set(providerID, info)
|
||||
return c.json(true)
|
||||
},
|
||||
)
|
||||
|
|
|
|||
|
|
@ -6,7 +6,7 @@ import { Session } from "@/session"
|
|||
import { MessageV2 } from "@/session/message-v2"
|
||||
import { Storage } from "@/storage/storage"
|
||||
import { Log } from "@/util/log"
|
||||
import type * as SDK from "@opencode-ai/sdk"
|
||||
import type * as SDK from "@opencode-ai/sdk/v2"
|
||||
|
||||
export namespace ShareNext {
|
||||
const log = Log.create({ service: "share-next" })
|
||||
|
|
|
|||
|
|
@ -181,7 +181,7 @@
|
|||
}
|
||||
}
|
||||
},
|
||||
"/pty/{id}": {
|
||||
"/pty/{ptyID}": {
|
||||
"get": {
|
||||
"operationId": "pty.get",
|
||||
"parameters": [
|
||||
|
|
@ -194,7 +194,7 @@
|
|||
},
|
||||
{
|
||||
"in": "path",
|
||||
"name": "id",
|
||||
"name": "ptyID",
|
||||
"schema": {
|
||||
"type": "string"
|
||||
},
|
||||
|
|
@ -237,7 +237,7 @@
|
|||
},
|
||||
{
|
||||
"in": "path",
|
||||
"name": "id",
|
||||
"name": "ptyID",
|
||||
"schema": {
|
||||
"type": "string"
|
||||
},
|
||||
|
|
@ -306,7 +306,7 @@
|
|||
},
|
||||
{
|
||||
"in": "path",
|
||||
"name": "id",
|
||||
"name": "ptyID",
|
||||
"schema": {
|
||||
"type": "string"
|
||||
},
|
||||
|
|
@ -338,7 +338,7 @@
|
|||
}
|
||||
}
|
||||
},
|
||||
"/pty/{id}/connect": {
|
||||
"/pty/{ptyID}/connect": {
|
||||
"get": {
|
||||
"operationId": "pty.connect",
|
||||
"parameters": [
|
||||
|
|
@ -351,7 +351,7 @@
|
|||
},
|
||||
{
|
||||
"in": "path",
|
||||
"name": "id",
|
||||
"name": "ptyID",
|
||||
"schema": {
|
||||
"type": "string"
|
||||
},
|
||||
|
|
@ -751,7 +751,7 @@
|
|||
}
|
||||
}
|
||||
},
|
||||
"/session/{id}": {
|
||||
"/session/{sessionID}": {
|
||||
"get": {
|
||||
"operationId": "session.get",
|
||||
"parameters": [
|
||||
|
|
@ -764,7 +764,7 @@
|
|||
},
|
||||
{
|
||||
"in": "path",
|
||||
"name": "id",
|
||||
"name": "sessionID",
|
||||
"schema": {
|
||||
"type": "string",
|
||||
"pattern": "^ses.*"
|
||||
|
|
@ -818,7 +818,7 @@
|
|||
},
|
||||
{
|
||||
"in": "path",
|
||||
"name": "id",
|
||||
"name": "sessionID",
|
||||
"schema": {
|
||||
"type": "string",
|
||||
"pattern": "^ses.*"
|
||||
|
|
@ -872,7 +872,7 @@
|
|||
},
|
||||
{
|
||||
"in": "path",
|
||||
"name": "id",
|
||||
"name": "sessionID",
|
||||
"schema": {
|
||||
"type": "string"
|
||||
},
|
||||
|
|
@ -928,7 +928,7 @@
|
|||
}
|
||||
}
|
||||
},
|
||||
"/session/{id}/children": {
|
||||
"/session/{sessionID}/children": {
|
||||
"get": {
|
||||
"operationId": "session.children",
|
||||
"parameters": [
|
||||
|
|
@ -941,7 +941,7 @@
|
|||
},
|
||||
{
|
||||
"in": "path",
|
||||
"name": "id",
|
||||
"name": "sessionID",
|
||||
"schema": {
|
||||
"type": "string",
|
||||
"pattern": "^ses.*"
|
||||
|
|
@ -987,7 +987,7 @@
|
|||
}
|
||||
}
|
||||
},
|
||||
"/session/{id}/todo": {
|
||||
"/session/{sessionID}/todo": {
|
||||
"get": {
|
||||
"operationId": "session.todo",
|
||||
"parameters": [
|
||||
|
|
@ -1000,7 +1000,7 @@
|
|||
},
|
||||
{
|
||||
"in": "path",
|
||||
"name": "id",
|
||||
"name": "sessionID",
|
||||
"schema": {
|
||||
"type": "string"
|
||||
},
|
||||
|
|
@ -1046,7 +1046,7 @@
|
|||
}
|
||||
}
|
||||
},
|
||||
"/session/{id}/init": {
|
||||
"/session/{sessionID}/init": {
|
||||
"post": {
|
||||
"operationId": "session.init",
|
||||
"parameters": [
|
||||
|
|
@ -1059,7 +1059,7 @@
|
|||
},
|
||||
{
|
||||
"in": "path",
|
||||
"name": "id",
|
||||
"name": "sessionID",
|
||||
"schema": {
|
||||
"type": "string"
|
||||
},
|
||||
|
|
@ -1124,7 +1124,7 @@
|
|||
}
|
||||
}
|
||||
},
|
||||
"/session/{id}/fork": {
|
||||
"/session/{sessionID}/fork": {
|
||||
"post": {
|
||||
"operationId": "session.fork",
|
||||
"parameters": [
|
||||
|
|
@ -1137,7 +1137,7 @@
|
|||
},
|
||||
{
|
||||
"in": "path",
|
||||
"name": "id",
|
||||
"name": "sessionID",
|
||||
"schema": {
|
||||
"type": "string",
|
||||
"pattern": "^ses.*"
|
||||
|
|
@ -1175,7 +1175,7 @@
|
|||
}
|
||||
}
|
||||
},
|
||||
"/session/{id}/abort": {
|
||||
"/session/{sessionID}/abort": {
|
||||
"post": {
|
||||
"operationId": "session.abort",
|
||||
"parameters": [
|
||||
|
|
@ -1188,7 +1188,7 @@
|
|||
},
|
||||
{
|
||||
"in": "path",
|
||||
"name": "id",
|
||||
"name": "sessionID",
|
||||
"schema": {
|
||||
"type": "string"
|
||||
},
|
||||
|
|
@ -1230,7 +1230,7 @@
|
|||
}
|
||||
}
|
||||
},
|
||||
"/session/{id}/share": {
|
||||
"/session/{sessionID}/share": {
|
||||
"post": {
|
||||
"operationId": "session.share",
|
||||
"parameters": [
|
||||
|
|
@ -1243,7 +1243,7 @@
|
|||
},
|
||||
{
|
||||
"in": "path",
|
||||
"name": "id",
|
||||
"name": "sessionID",
|
||||
"schema": {
|
||||
"type": "string"
|
||||
},
|
||||
|
|
@ -1296,7 +1296,7 @@
|
|||
},
|
||||
{
|
||||
"in": "path",
|
||||
"name": "id",
|
||||
"name": "sessionID",
|
||||
"schema": {
|
||||
"type": "string",
|
||||
"pattern": "^ses.*"
|
||||
|
|
@ -1339,7 +1339,7 @@
|
|||
}
|
||||
}
|
||||
},
|
||||
"/session/{id}/diff": {
|
||||
"/session/{sessionID}/diff": {
|
||||
"get": {
|
||||
"operationId": "session.diff",
|
||||
"parameters": [
|
||||
|
|
@ -1352,7 +1352,7 @@
|
|||
},
|
||||
{
|
||||
"in": "path",
|
||||
"name": "id",
|
||||
"name": "sessionID",
|
||||
"schema": {
|
||||
"type": "string"
|
||||
},
|
||||
|
|
@ -1406,7 +1406,7 @@
|
|||
}
|
||||
}
|
||||
},
|
||||
"/session/{id}/summarize": {
|
||||
"/session/{sessionID}/summarize": {
|
||||
"post": {
|
||||
"operationId": "session.summarize",
|
||||
"parameters": [
|
||||
|
|
@ -1419,7 +1419,7 @@
|
|||
},
|
||||
{
|
||||
"in": "path",
|
||||
"name": "id",
|
||||
"name": "sessionID",
|
||||
"schema": {
|
||||
"type": "string"
|
||||
},
|
||||
|
|
@ -1480,7 +1480,7 @@
|
|||
}
|
||||
}
|
||||
},
|
||||
"/session/{id}/message": {
|
||||
"/session/{sessionID}/message": {
|
||||
"get": {
|
||||
"operationId": "session.messages",
|
||||
"parameters": [
|
||||
|
|
@ -1493,7 +1493,7 @@
|
|||
},
|
||||
{
|
||||
"in": "path",
|
||||
"name": "id",
|
||||
"name": "sessionID",
|
||||
"schema": {
|
||||
"type": "string"
|
||||
},
|
||||
|
|
@ -1569,7 +1569,7 @@
|
|||
},
|
||||
{
|
||||
"in": "path",
|
||||
"name": "id",
|
||||
"name": "sessionID",
|
||||
"schema": {
|
||||
"type": "string"
|
||||
},
|
||||
|
|
@ -1689,7 +1689,7 @@
|
|||
}
|
||||
}
|
||||
},
|
||||
"/session/{id}/message/{messageID}": {
|
||||
"/session/{sessionID}/message/{messageID}": {
|
||||
"get": {
|
||||
"operationId": "session.message",
|
||||
"parameters": [
|
||||
|
|
@ -1702,7 +1702,7 @@
|
|||
},
|
||||
{
|
||||
"in": "path",
|
||||
"name": "id",
|
||||
"name": "sessionID",
|
||||
"schema": {
|
||||
"type": "string"
|
||||
},
|
||||
|
|
@ -1766,7 +1766,7 @@
|
|||
}
|
||||
}
|
||||
},
|
||||
"/session/{id}/prompt_async": {
|
||||
"/session/{sessionID}/prompt_async": {
|
||||
"post": {
|
||||
"operationId": "session.prompt_async",
|
||||
"parameters": [
|
||||
|
|
@ -1779,7 +1779,7 @@
|
|||
},
|
||||
{
|
||||
"in": "path",
|
||||
"name": "id",
|
||||
"name": "sessionID",
|
||||
"schema": {
|
||||
"type": "string"
|
||||
},
|
||||
|
|
@ -1880,7 +1880,7 @@
|
|||
}
|
||||
}
|
||||
},
|
||||
"/session/{id}/command": {
|
||||
"/session/{sessionID}/command": {
|
||||
"post": {
|
||||
"operationId": "session.command",
|
||||
"parameters": [
|
||||
|
|
@ -1893,7 +1893,7 @@
|
|||
},
|
||||
{
|
||||
"in": "path",
|
||||
"name": "id",
|
||||
"name": "sessionID",
|
||||
"schema": {
|
||||
"type": "string"
|
||||
},
|
||||
|
|
@ -1976,7 +1976,7 @@
|
|||
}
|
||||
}
|
||||
},
|
||||
"/session/{id}/shell": {
|
||||
"/session/{sessionID}/shell": {
|
||||
"post": {
|
||||
"operationId": "session.shell",
|
||||
"parameters": [
|
||||
|
|
@ -1989,7 +1989,7 @@
|
|||
},
|
||||
{
|
||||
"in": "path",
|
||||
"name": "id",
|
||||
"name": "sessionID",
|
||||
"schema": {
|
||||
"type": "string"
|
||||
},
|
||||
|
|
@ -2062,7 +2062,7 @@
|
|||
}
|
||||
}
|
||||
},
|
||||
"/session/{id}/revert": {
|
||||
"/session/{sessionID}/revert": {
|
||||
"post": {
|
||||
"operationId": "session.revert",
|
||||
"parameters": [
|
||||
|
|
@ -2075,7 +2075,7 @@
|
|||
},
|
||||
{
|
||||
"in": "path",
|
||||
"name": "id",
|
||||
"name": "sessionID",
|
||||
"schema": {
|
||||
"type": "string"
|
||||
},
|
||||
|
|
@ -2137,7 +2137,7 @@
|
|||
}
|
||||
}
|
||||
},
|
||||
"/session/{id}/unrevert": {
|
||||
"/session/{sessionID}/unrevert": {
|
||||
"post": {
|
||||
"operationId": "session.unrevert",
|
||||
"parameters": [
|
||||
|
|
@ -2150,7 +2150,7 @@
|
|||
},
|
||||
{
|
||||
"in": "path",
|
||||
"name": "id",
|
||||
"name": "sessionID",
|
||||
"schema": {
|
||||
"type": "string"
|
||||
},
|
||||
|
|
@ -2192,9 +2192,9 @@
|
|||
}
|
||||
}
|
||||
},
|
||||
"/session/{id}/permissions/{permissionID}": {
|
||||
"/session/{sessionID}/permissions/{permissionID}": {
|
||||
"post": {
|
||||
"operationId": "postSession:idPermissions:permissionID",
|
||||
"operationId": "permission.respond",
|
||||
"parameters": [
|
||||
{
|
||||
"in": "query",
|
||||
|
|
@ -2205,7 +2205,7 @@
|
|||
},
|
||||
{
|
||||
"in": "path",
|
||||
"name": "id",
|
||||
"name": "sessionID",
|
||||
"schema": {
|
||||
"type": "string"
|
||||
},
|
||||
|
|
@ -2597,7 +2597,7 @@
|
|||
}
|
||||
}
|
||||
},
|
||||
"/provider/{id}/oauth/authorize": {
|
||||
"/provider/{providerID}/oauth/authorize": {
|
||||
"post": {
|
||||
"operationId": "provider.oauth.authorize",
|
||||
"parameters": [
|
||||
|
|
@ -2610,7 +2610,7 @@
|
|||
},
|
||||
{
|
||||
"in": "path",
|
||||
"name": "id",
|
||||
"name": "providerID",
|
||||
"schema": {
|
||||
"type": "string"
|
||||
},
|
||||
|
|
@ -2659,7 +2659,7 @@
|
|||
}
|
||||
}
|
||||
},
|
||||
"/provider/{id}/oauth/callback": {
|
||||
"/provider/{providerID}/oauth/callback": {
|
||||
"post": {
|
||||
"operationId": "provider.oauth.callback",
|
||||
"parameters": [
|
||||
|
|
@ -2672,7 +2672,7 @@
|
|||
},
|
||||
{
|
||||
"in": "path",
|
||||
"name": "id",
|
||||
"name": "providerID",
|
||||
"schema": {
|
||||
"type": "string"
|
||||
},
|
||||
|
|
@ -3942,7 +3942,7 @@
|
|||
}
|
||||
}
|
||||
},
|
||||
"/auth/{id}": {
|
||||
"/auth/{providerID}": {
|
||||
"put": {
|
||||
"operationId": "auth.set",
|
||||
"parameters": [
|
||||
|
|
@ -3955,7 +3955,7 @@
|
|||
},
|
||||
{
|
||||
"in": "path",
|
||||
"name": "id",
|
||||
"name": "providerID",
|
||||
"schema": {
|
||||
"type": "string"
|
||||
},
|
||||
|
|
|
|||
|
|
@ -10,13 +10,16 @@
|
|||
"exports": {
|
||||
".": "./src/index.ts",
|
||||
"./client": "./src/client.ts",
|
||||
"./server": "./src/server.ts"
|
||||
"./server": "./src/server.ts",
|
||||
"./v2": "./src/v2/index.ts",
|
||||
"./v2/client": "./src/v2/client.ts",
|
||||
"./v2/server": "./src/v2/server.ts"
|
||||
},
|
||||
"files": [
|
||||
"dist"
|
||||
],
|
||||
"devDependencies": {
|
||||
"@hey-api/openapi-ts": "0.81.0",
|
||||
"@hey-api/openapi-ts": "0.88.0",
|
||||
"@tsconfig/node22": "catalog:",
|
||||
"@types/node": "catalog:",
|
||||
"typescript": "catalog:",
|
||||
|
|
|
|||
|
|
@ -17,6 +17,7 @@ await createClient({
|
|||
output: {
|
||||
path: "./src/gen",
|
||||
tsConfigPath: path.join(dir, "tsconfig.json"),
|
||||
clean: true,
|
||||
},
|
||||
plugins: [
|
||||
{
|
||||
|
|
@ -36,6 +37,33 @@ await createClient({
|
|||
},
|
||||
],
|
||||
})
|
||||
await createClient({
|
||||
input: "./openapi.json",
|
||||
output: {
|
||||
path: "./src/v2/gen",
|
||||
tsConfigPath: path.join(dir, "tsconfig.json"),
|
||||
clean: true,
|
||||
},
|
||||
plugins: [
|
||||
{
|
||||
name: "@hey-api/typescript",
|
||||
exportFromIndex: false,
|
||||
},
|
||||
{
|
||||
name: "@hey-api/sdk",
|
||||
instance: "OpencodeClient",
|
||||
exportFromIndex: false,
|
||||
auth: false,
|
||||
paramsStructure: "flat",
|
||||
},
|
||||
{
|
||||
name: "@hey-api/client-fetch",
|
||||
exportFromIndex: false,
|
||||
baseUrl: "http://localhost:4096",
|
||||
},
|
||||
],
|
||||
})
|
||||
|
||||
await $`bun prettier --write src/gen`
|
||||
await $`rm -rf dist`
|
||||
await $`bun tsc`
|
||||
|
|
|
|||
|
|
@ -1,19 +1,20 @@
|
|||
export * from "./gen/types.gen.js"
|
||||
export { type Config as OpencodeClientConfig, OpencodeClient }
|
||||
|
||||
import { createClient } from "./gen/client/client.gen.js"
|
||||
import { type Config } from "./gen/client/types.gen.js"
|
||||
import { OpencodeClient } from "./gen/sdk.gen.js"
|
||||
export { type Config as OpencodeClientConfig, OpencodeClient }
|
||||
|
||||
export function createOpencodeClient(config?: Config & { directory?: string }) {
|
||||
if (!config?.fetch) {
|
||||
const customFetch: any = (req: any) => {
|
||||
// @ts-ignore
|
||||
req.timeout = false
|
||||
return fetch(req)
|
||||
}
|
||||
config = {
|
||||
...config,
|
||||
fetch: (req) => {
|
||||
// @ts-ignore
|
||||
req.timeout = false
|
||||
return fetch(req)
|
||||
},
|
||||
fetch: customFetch,
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
// This file is auto-generated by @hey-api/openapi-ts
|
||||
|
||||
import type { ClientOptions } from "./types.gen.js"
|
||||
import { type Config, type ClientOptions as DefaultClientOptions, createClient, createConfig } from "./client/index.js"
|
||||
import { type ClientOptions, type Config, createClient, createConfig } from "./client/index.js"
|
||||
import type { ClientOptions as ClientOptions2 } from "./types.gen.js"
|
||||
|
||||
/**
|
||||
* The `createClientConfig()` function will be called on client initialization
|
||||
|
|
@ -11,12 +11,8 @@ import { type Config, type ClientOptions as DefaultClientOptions, createClient,
|
|||
* `setConfig()`. This is useful for example if you're using Next.js
|
||||
* to ensure your client always has the correct values.
|
||||
*/
|
||||
export type CreateClientConfig<T extends DefaultClientOptions = ClientOptions> = (
|
||||
override?: Config<DefaultClientOptions & T>,
|
||||
) => Config<Required<DefaultClientOptions> & T>
|
||||
export type CreateClientConfig<T extends ClientOptions = ClientOptions2> = (
|
||||
override?: Config<ClientOptions & T>,
|
||||
) => Config<Required<ClientOptions> & T>
|
||||
|
||||
export const client = createClient(
|
||||
createConfig<ClientOptions>({
|
||||
baseUrl: "http://localhost:4096",
|
||||
}),
|
||||
)
|
||||
export const client = createClient(createConfig<ClientOptions2>({ baseUrl: "http://localhost:4096" }))
|
||||
|
|
|
|||
|
|
@ -1,6 +1,8 @@
|
|||
// This file is auto-generated by @hey-api/openapi-ts
|
||||
|
||||
import { createSseClient } from "../core/serverSentEvents.gen.js"
|
||||
import type { HttpMethod } from "../core/types.gen.js"
|
||||
import { getValidRequestBody } from "../core/utils.gen.js"
|
||||
import type { Client, Config, RequestOptions, ResolvedRequestOptions } from "./types.gen.js"
|
||||
import {
|
||||
buildUrl,
|
||||
|
|
@ -49,12 +51,12 @@ export const createClient = (config: Config = {}): Client => {
|
|||
await opts.requestValidator(opts)
|
||||
}
|
||||
|
||||
if (opts.body && opts.bodySerializer) {
|
||||
if (opts.body !== undefined && opts.bodySerializer) {
|
||||
opts.serializedBody = opts.bodySerializer(opts.body)
|
||||
}
|
||||
|
||||
// remove Content-Type header if body is empty to avoid sending invalid requests
|
||||
if (opts.serializedBody === undefined || opts.serializedBody === "") {
|
||||
if (opts.body === undefined || opts.serializedBody === "") {
|
||||
opts.headers.delete("Content-Type")
|
||||
}
|
||||
|
||||
|
|
@ -69,12 +71,12 @@ export const createClient = (config: Config = {}): Client => {
|
|||
const requestInit: ReqInit = {
|
||||
redirect: "follow",
|
||||
...opts,
|
||||
body: opts.serializedBody,
|
||||
body: getValidRequestBody(opts),
|
||||
}
|
||||
|
||||
let request = new Request(url, requestInit)
|
||||
|
||||
for (const fn of interceptors.request._fns) {
|
||||
for (const fn of interceptors.request.fns) {
|
||||
if (fn) {
|
||||
request = await fn(request, opts)
|
||||
}
|
||||
|
|
@ -83,9 +85,37 @@ export const createClient = (config: Config = {}): Client => {
|
|||
// fetch must be assigned here, otherwise it would throw the error:
|
||||
// TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation
|
||||
const _fetch = opts.fetch!
|
||||
let response = await _fetch(request)
|
||||
let response: Response
|
||||
|
||||
for (const fn of interceptors.response._fns) {
|
||||
try {
|
||||
response = await _fetch(request)
|
||||
} catch (error) {
|
||||
// Handle fetch exceptions (AbortError, network errors, etc.)
|
||||
let finalError = error
|
||||
|
||||
for (const fn of interceptors.error.fns) {
|
||||
if (fn) {
|
||||
finalError = (await fn(error, undefined as any, request, opts)) as unknown
|
||||
}
|
||||
}
|
||||
|
||||
finalError = finalError || ({} as unknown)
|
||||
|
||||
if (opts.throwOnError) {
|
||||
throw finalError
|
||||
}
|
||||
|
||||
// Return error response
|
||||
return opts.responseStyle === "data"
|
||||
? undefined
|
||||
: {
|
||||
error: finalError,
|
||||
request,
|
||||
response: undefined as any,
|
||||
}
|
||||
}
|
||||
|
||||
for (const fn of interceptors.response.fns) {
|
||||
if (fn) {
|
||||
response = await fn(response, request, opts)
|
||||
}
|
||||
|
|
@ -97,18 +127,36 @@ export const createClient = (config: Config = {}): Client => {
|
|||
}
|
||||
|
||||
if (response.ok) {
|
||||
const parseAs =
|
||||
(opts.parseAs === "auto" ? getParseAs(response.headers.get("Content-Type")) : opts.parseAs) ?? "json"
|
||||
|
||||
if (response.status === 204 || response.headers.get("Content-Length") === "0") {
|
||||
let emptyData: any
|
||||
switch (parseAs) {
|
||||
case "arrayBuffer":
|
||||
case "blob":
|
||||
case "text":
|
||||
emptyData = await response[parseAs]()
|
||||
break
|
||||
case "formData":
|
||||
emptyData = new FormData()
|
||||
break
|
||||
case "stream":
|
||||
emptyData = response.body
|
||||
break
|
||||
case "json":
|
||||
default:
|
||||
emptyData = {}
|
||||
break
|
||||
}
|
||||
return opts.responseStyle === "data"
|
||||
? {}
|
||||
? emptyData
|
||||
: {
|
||||
data: {},
|
||||
data: emptyData,
|
||||
...result,
|
||||
}
|
||||
}
|
||||
|
||||
const parseAs =
|
||||
(opts.parseAs === "auto" ? getParseAs(response.headers.get("Content-Type")) : opts.parseAs) ?? "json"
|
||||
|
||||
let data: any
|
||||
switch (parseAs) {
|
||||
case "arrayBuffer":
|
||||
|
|
@ -157,7 +205,7 @@ export const createClient = (config: Config = {}): Client => {
|
|||
const error = jsonError ?? textError
|
||||
let finalError = error
|
||||
|
||||
for (const fn of interceptors.error._fns) {
|
||||
for (const fn of interceptors.error.fns) {
|
||||
if (fn) {
|
||||
finalError = (await fn(error, response, request, opts)) as string
|
||||
}
|
||||
|
|
@ -178,35 +226,53 @@ export const createClient = (config: Config = {}): Client => {
|
|||
}
|
||||
}
|
||||
|
||||
const makeMethod = (method: Required<Config>["method"]) => {
|
||||
const fn = (options: RequestOptions) => request({ ...options, method })
|
||||
fn.sse = async (options: RequestOptions) => {
|
||||
const { opts, url } = await beforeRequest(options)
|
||||
return createSseClient({
|
||||
...opts,
|
||||
body: opts.body as BodyInit | null | undefined,
|
||||
headers: opts.headers as unknown as Record<string, string>,
|
||||
method,
|
||||
url,
|
||||
})
|
||||
}
|
||||
return fn
|
||||
const makeMethodFn = (method: Uppercase<HttpMethod>) => (options: RequestOptions) => request({ ...options, method })
|
||||
|
||||
const makeSseFn = (method: Uppercase<HttpMethod>) => async (options: RequestOptions) => {
|
||||
const { opts, url } = await beforeRequest(options)
|
||||
return createSseClient({
|
||||
...opts,
|
||||
body: opts.body as BodyInit | null | undefined,
|
||||
headers: opts.headers as unknown as Record<string, string>,
|
||||
method,
|
||||
onRequest: async (url, init) => {
|
||||
let request = new Request(url, init)
|
||||
for (const fn of interceptors.request.fns) {
|
||||
if (fn) {
|
||||
request = await fn(request, opts)
|
||||
}
|
||||
}
|
||||
return request
|
||||
},
|
||||
url,
|
||||
})
|
||||
}
|
||||
|
||||
return {
|
||||
buildUrl,
|
||||
connect: makeMethod("CONNECT"),
|
||||
delete: makeMethod("DELETE"),
|
||||
get: makeMethod("GET"),
|
||||
connect: makeMethodFn("CONNECT"),
|
||||
delete: makeMethodFn("DELETE"),
|
||||
get: makeMethodFn("GET"),
|
||||
getConfig,
|
||||
head: makeMethod("HEAD"),
|
||||
head: makeMethodFn("HEAD"),
|
||||
interceptors,
|
||||
options: makeMethod("OPTIONS"),
|
||||
patch: makeMethod("PATCH"),
|
||||
post: makeMethod("POST"),
|
||||
put: makeMethod("PUT"),
|
||||
options: makeMethodFn("OPTIONS"),
|
||||
patch: makeMethodFn("PATCH"),
|
||||
post: makeMethodFn("POST"),
|
||||
put: makeMethodFn("PUT"),
|
||||
request,
|
||||
setConfig,
|
||||
trace: makeMethod("TRACE"),
|
||||
sse: {
|
||||
connect: makeSseFn("CONNECT"),
|
||||
delete: makeSseFn("DELETE"),
|
||||
get: makeSseFn("GET"),
|
||||
head: makeSseFn("HEAD"),
|
||||
options: makeSseFn("OPTIONS"),
|
||||
patch: makeSseFn("PATCH"),
|
||||
post: makeSseFn("POST"),
|
||||
put: makeSseFn("PUT"),
|
||||
trace: makeSseFn("TRACE"),
|
||||
},
|
||||
trace: makeMethodFn("TRACE"),
|
||||
} as Client
|
||||
}
|
||||
|
|
|
|||
|
|
@ -8,6 +8,7 @@ export {
|
|||
urlSearchParamsBodySerializer,
|
||||
} from "../core/bodySerializer.gen.js"
|
||||
export { buildClientParams } from "../core/params.gen.js"
|
||||
export { serializeQueryKeyValue } from "../core/queryKeySerializer.gen.js"
|
||||
export { createClient } from "./client.gen.js"
|
||||
export type {
|
||||
Client,
|
||||
|
|
@ -15,7 +16,6 @@ export type {
|
|||
Config,
|
||||
CreateClientConfig,
|
||||
Options,
|
||||
OptionsLegacyParser,
|
||||
RequestOptions,
|
||||
RequestResult,
|
||||
ResolvedRequestOptions,
|
||||
|
|
|
|||
|
|
@ -20,7 +20,7 @@ export interface Config<T extends ClientOptions = ClientOptions>
|
|||
*
|
||||
* @default globalThis.fetch
|
||||
*/
|
||||
fetch?: (request: Request) => ReturnType<typeof fetch>
|
||||
fetch?: typeof fetch
|
||||
/**
|
||||
* Please don't use the Fetch client for Next.js applications. The `next`
|
||||
* options won't have any effect.
|
||||
|
|
@ -128,7 +128,7 @@ export interface ClientOptions {
|
|||
throwOnError?: boolean
|
||||
}
|
||||
|
||||
type MethodFnBase = <
|
||||
type MethodFn = <
|
||||
TData = unknown,
|
||||
TError = unknown,
|
||||
ThrowOnError extends boolean = false,
|
||||
|
|
@ -137,7 +137,7 @@ type MethodFnBase = <
|
|||
options: Omit<RequestOptions<TData, TResponseStyle, ThrowOnError>, "method">,
|
||||
) => RequestResult<TData, TError, ThrowOnError, TResponseStyle>
|
||||
|
||||
type MethodFnServerSentEvents = <
|
||||
type SseFn = <
|
||||
TData = unknown,
|
||||
TError = unknown,
|
||||
ThrowOnError extends boolean = false,
|
||||
|
|
@ -146,10 +146,6 @@ type MethodFnServerSentEvents = <
|
|||
options: Omit<RequestOptions<TData, TResponseStyle, ThrowOnError>, "method">,
|
||||
) => Promise<ServerSentEventsResult<TData, TError>>
|
||||
|
||||
type MethodFn = MethodFnBase & {
|
||||
sse: MethodFnServerSentEvents
|
||||
}
|
||||
|
||||
type RequestFn = <
|
||||
TData = unknown,
|
||||
TError = unknown,
|
||||
|
|
@ -168,10 +164,10 @@ type BuildUrlFn = <
|
|||
url: string
|
||||
},
|
||||
>(
|
||||
options: Pick<TData, "url"> & Options<TData>,
|
||||
options: TData & Options<TData>,
|
||||
) => string
|
||||
|
||||
export type Client = CoreClient<RequestFn, Config, MethodFn, BuildUrlFn> & {
|
||||
export type Client = CoreClient<RequestFn, Config, MethodFn, BuildUrlFn, SseFn> & {
|
||||
interceptors: Middleware<Request, Response, unknown, ResolvedRequestOptions>
|
||||
}
|
||||
|
||||
|
|
@ -203,20 +199,4 @@ export type Options<
|
|||
TResponse = unknown,
|
||||
TResponseStyle extends ResponseStyle = "fields",
|
||||
> = OmitKeys<RequestOptions<TResponse, TResponseStyle, ThrowOnError>, "body" | "path" | "query" | "url"> &
|
||||
Omit<TData, "url">
|
||||
|
||||
export type OptionsLegacyParser<
|
||||
TData = unknown,
|
||||
ThrowOnError extends boolean = boolean,
|
||||
TResponseStyle extends ResponseStyle = "fields",
|
||||
> = TData extends { body?: any }
|
||||
? TData extends { headers?: any }
|
||||
? OmitKeys<RequestOptions<unknown, TResponseStyle, ThrowOnError>, "body" | "headers" | "url"> & TData
|
||||
: OmitKeys<RequestOptions<unknown, TResponseStyle, ThrowOnError>, "body" | "url"> &
|
||||
TData &
|
||||
Pick<RequestOptions<unknown, TResponseStyle, ThrowOnError>, "headers">
|
||||
: TData extends { headers?: any }
|
||||
? OmitKeys<RequestOptions<unknown, TResponseStyle, ThrowOnError>, "headers" | "url"> &
|
||||
TData &
|
||||
Pick<RequestOptions<unknown, TResponseStyle, ThrowOnError>, "body">
|
||||
: OmitKeys<RequestOptions<unknown, TResponseStyle, ThrowOnError>, "url"> & TData
|
||||
([TData] extends [never] ? unknown : Omit<TData, "url">)
|
||||
|
|
|
|||
|
|
@ -7,7 +7,7 @@ import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam } fr
|
|||
import { getUrl } from "../core/utils.gen.js"
|
||||
import type { Client, ClientOptions, Config, RequestOptions } from "./types.gen.js"
|
||||
|
||||
export const createQuerySerializer = <T = unknown>({ allowReserved, array, object }: QuerySerializerOptions = {}) => {
|
||||
export const createQuerySerializer = <T = unknown>({ parameters = {}, ...args }: QuerySerializerOptions = {}) => {
|
||||
const querySerializer = (queryParams: T) => {
|
||||
const search: string[] = []
|
||||
if (queryParams && typeof queryParams === "object") {
|
||||
|
|
@ -18,29 +18,31 @@ export const createQuerySerializer = <T = unknown>({ allowReserved, array, objec
|
|||
continue
|
||||
}
|
||||
|
||||
const options = parameters[name] || args
|
||||
|
||||
if (Array.isArray(value)) {
|
||||
const serializedArray = serializeArrayParam({
|
||||
allowReserved,
|
||||
allowReserved: options.allowReserved,
|
||||
explode: true,
|
||||
name,
|
||||
style: "form",
|
||||
value,
|
||||
...array,
|
||||
...options.array,
|
||||
})
|
||||
if (serializedArray) search.push(serializedArray)
|
||||
} else if (typeof value === "object") {
|
||||
const serializedObject = serializeObjectParam({
|
||||
allowReserved,
|
||||
allowReserved: options.allowReserved,
|
||||
explode: true,
|
||||
name,
|
||||
style: "deepObject",
|
||||
value: value as Record<string, unknown>,
|
||||
...object,
|
||||
...options.object,
|
||||
})
|
||||
if (serializedObject) search.push(serializedObject)
|
||||
} else {
|
||||
const serializedPrimitive = serializePrimitiveParam({
|
||||
allowReserved,
|
||||
allowReserved: options.allowReserved,
|
||||
name,
|
||||
value: value as string,
|
||||
})
|
||||
|
|
@ -162,14 +164,22 @@ export const mergeConfigs = (a: Config, b: Config): Config => {
|
|||
return config
|
||||
}
|
||||
|
||||
const headersEntries = (headers: Headers): Array<[string, string]> => {
|
||||
const entries: Array<[string, string]> = []
|
||||
headers.forEach((value, key) => {
|
||||
entries.push([key, value])
|
||||
})
|
||||
return entries
|
||||
}
|
||||
|
||||
export const mergeHeaders = (...headers: Array<Required<Config>["headers"] | undefined>): Headers => {
|
||||
const mergedHeaders = new Headers()
|
||||
for (const header of headers) {
|
||||
if (!header || typeof header !== "object") {
|
||||
if (!header) {
|
||||
continue
|
||||
}
|
||||
|
||||
const iterator = header instanceof Headers ? header.entries() : Object.entries(header)
|
||||
const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header)
|
||||
|
||||
for (const [key, value] of iterator) {
|
||||
if (value === null) {
|
||||
|
|
@ -200,61 +210,53 @@ type ReqInterceptor<Req, Options> = (request: Req, options: Options) => Req | Pr
|
|||
type ResInterceptor<Res, Req, Options> = (response: Res, request: Req, options: Options) => Res | Promise<Res>
|
||||
|
||||
class Interceptors<Interceptor> {
|
||||
_fns: (Interceptor | null)[]
|
||||
fns: Array<Interceptor | null> = []
|
||||
|
||||
constructor() {
|
||||
this._fns = []
|
||||
clear(): void {
|
||||
this.fns = []
|
||||
}
|
||||
|
||||
clear() {
|
||||
this._fns = []
|
||||
eject(id: number | Interceptor): void {
|
||||
const index = this.getInterceptorIndex(id)
|
||||
if (this.fns[index]) {
|
||||
this.fns[index] = null
|
||||
}
|
||||
}
|
||||
|
||||
exists(id: number | Interceptor): boolean {
|
||||
const index = this.getInterceptorIndex(id)
|
||||
return Boolean(this.fns[index])
|
||||
}
|
||||
|
||||
getInterceptorIndex(id: number | Interceptor): number {
|
||||
if (typeof id === "number") {
|
||||
return this._fns[id] ? id : -1
|
||||
} else {
|
||||
return this._fns.indexOf(id)
|
||||
return this.fns[id] ? id : -1
|
||||
}
|
||||
}
|
||||
exists(id: number | Interceptor) {
|
||||
const index = this.getInterceptorIndex(id)
|
||||
return !!this._fns[index]
|
||||
return this.fns.indexOf(id)
|
||||
}
|
||||
|
||||
eject(id: number | Interceptor) {
|
||||
update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false {
|
||||
const index = this.getInterceptorIndex(id)
|
||||
if (this._fns[index]) {
|
||||
this._fns[index] = null
|
||||
}
|
||||
}
|
||||
|
||||
update(id: number | Interceptor, fn: Interceptor) {
|
||||
const index = this.getInterceptorIndex(id)
|
||||
if (this._fns[index]) {
|
||||
this._fns[index] = fn
|
||||
if (this.fns[index]) {
|
||||
this.fns[index] = fn
|
||||
return id
|
||||
} else {
|
||||
return false
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
use(fn: Interceptor) {
|
||||
this._fns = [...this._fns, fn]
|
||||
return this._fns.length - 1
|
||||
use(fn: Interceptor): number {
|
||||
this.fns.push(fn)
|
||||
return this.fns.length - 1
|
||||
}
|
||||
}
|
||||
|
||||
// `createInterceptors()` response, meant for external use as it does not
|
||||
// expose internals
|
||||
export interface Middleware<Req, Res, Err, Options> {
|
||||
error: Pick<Interceptors<ErrInterceptor<Err, Res, Req, Options>>, "eject" | "use">
|
||||
request: Pick<Interceptors<ReqInterceptor<Req, Options>>, "eject" | "use">
|
||||
response: Pick<Interceptors<ResInterceptor<Res, Req, Options>>, "eject" | "use">
|
||||
error: Interceptors<ErrInterceptor<Err, Res, Req, Options>>
|
||||
request: Interceptors<ReqInterceptor<Req, Options>>
|
||||
response: Interceptors<ResInterceptor<Res, Req, Options>>
|
||||
}
|
||||
|
||||
// do not add `Middleware` as return type so we can use _fns internally
|
||||
export const createInterceptors = <Req, Res, Err, Options>() => ({
|
||||
export const createInterceptors = <Req, Res, Err, Options>(): Middleware<Req, Res, Err, Options> => ({
|
||||
error: new Interceptors<ErrInterceptor<Err, Res, Req, Options>>(),
|
||||
request: new Interceptors<ReqInterceptor<Req, Options>>(),
|
||||
response: new Interceptors<ResInterceptor<Res, Req, Options>>(),
|
||||
|
|
|
|||
|
|
@ -6,10 +6,18 @@ export type QuerySerializer = (query: Record<string, unknown>) => string
|
|||
|
||||
export type BodySerializer = (body: any) => any
|
||||
|
||||
export interface QuerySerializerOptions {
|
||||
type QuerySerializerOptionsObject = {
|
||||
allowReserved?: boolean
|
||||
array?: SerializerOptions<ArrayStyle>
|
||||
object?: SerializerOptions<ObjectStyle>
|
||||
array?: Partial<SerializerOptions<ArrayStyle>>
|
||||
object?: Partial<SerializerOptions<ObjectStyle>>
|
||||
}
|
||||
|
||||
export type QuerySerializerOptions = QuerySerializerOptionsObject & {
|
||||
/**
|
||||
* Per-parameter serialization overrides. When provided, these settings
|
||||
* override the global array/object settings for specific parameter names.
|
||||
*/
|
||||
parameters?: Record<string, QuerySerializerOptionsObject>
|
||||
}
|
||||
|
||||
const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => {
|
||||
|
|
|
|||
|
|
@ -23,6 +23,17 @@ export type Field =
|
|||
key?: string
|
||||
map?: string
|
||||
}
|
||||
| {
|
||||
/**
|
||||
* Field name. This is the name we want the user to see and use.
|
||||
*/
|
||||
key: string
|
||||
/**
|
||||
* Field mapped name. This is the name we want to use in the request.
|
||||
* If `in` is omitted, `map` aliases `key` to the transport layer.
|
||||
*/
|
||||
map: Slot
|
||||
}
|
||||
|
||||
export interface Fields {
|
||||
allowExtra?: Partial<Record<Slot, boolean>>
|
||||
|
|
@ -41,10 +52,14 @@ const extraPrefixes = Object.entries(extraPrefixesMap)
|
|||
|
||||
type KeyMap = Map<
|
||||
string,
|
||||
{
|
||||
in: Slot
|
||||
map?: string
|
||||
}
|
||||
| {
|
||||
in: Slot
|
||||
map?: string
|
||||
}
|
||||
| {
|
||||
in?: never
|
||||
map: Slot
|
||||
}
|
||||
>
|
||||
|
||||
const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => {
|
||||
|
|
@ -60,6 +75,10 @@ const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => {
|
|||
map: config.map,
|
||||
})
|
||||
}
|
||||
} else if ("key" in config) {
|
||||
map.set(config.key, {
|
||||
map: config.map,
|
||||
})
|
||||
} else if (config.args) {
|
||||
buildKeyMap(config.args, map)
|
||||
}
|
||||
|
|
@ -108,7 +127,9 @@ export const buildClientParams = (args: ReadonlyArray<unknown>, fields: FieldsCo
|
|||
if (config.key) {
|
||||
const field = map.get(config.key)!
|
||||
const name = field.map || config.key
|
||||
;(params[field.in] as Record<string, unknown>)[name] = arg
|
||||
if (field.in) {
|
||||
;(params[field.in] as Record<string, unknown>)[name] = arg
|
||||
}
|
||||
} else {
|
||||
params.body = arg
|
||||
}
|
||||
|
|
@ -117,16 +138,20 @@ export const buildClientParams = (args: ReadonlyArray<unknown>, fields: FieldsCo
|
|||
const field = map.get(key)
|
||||
|
||||
if (field) {
|
||||
const name = field.map || key
|
||||
;(params[field.in] as Record<string, unknown>)[name] = value
|
||||
if (field.in) {
|
||||
const name = field.map || key
|
||||
;(params[field.in] as Record<string, unknown>)[name] = value
|
||||
} else {
|
||||
params[field.map] = value
|
||||
}
|
||||
} else {
|
||||
const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix))
|
||||
|
||||
if (extra) {
|
||||
const [prefix, slot] = extra
|
||||
;(params[slot] as Record<string, unknown>)[key.slice(prefix.length)] = value
|
||||
} else {
|
||||
for (const [slot, allowed] of Object.entries(config.allowExtra ?? {})) {
|
||||
} else if ("allowExtra" in config && config.allowExtra) {
|
||||
for (const [slot, allowed] of Object.entries(config.allowExtra)) {
|
||||
if (allowed) {
|
||||
;(params[slot as Slot] as Record<string, unknown>)[key] = value
|
||||
break
|
||||
|
|
|
|||
111
packages/sdk/js/src/gen/core/queryKeySerializer.gen.ts
Normal file
111
packages/sdk/js/src/gen/core/queryKeySerializer.gen.ts
Normal file
|
|
@ -0,0 +1,111 @@
|
|||
// This file is auto-generated by @hey-api/openapi-ts
|
||||
|
||||
/**
|
||||
* JSON-friendly union that mirrors what Pinia Colada can hash.
|
||||
*/
|
||||
export type JsonValue = null | string | number | boolean | JsonValue[] | { [key: string]: JsonValue }
|
||||
|
||||
/**
|
||||
* Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes.
|
||||
*/
|
||||
export const queryKeyJsonReplacer = (_key: string, value: unknown) => {
|
||||
if (value === undefined || typeof value === "function" || typeof value === "symbol") {
|
||||
return undefined
|
||||
}
|
||||
if (typeof value === "bigint") {
|
||||
return value.toString()
|
||||
}
|
||||
if (value instanceof Date) {
|
||||
return value.toISOString()
|
||||
}
|
||||
return value
|
||||
}
|
||||
|
||||
/**
|
||||
* Safely stringifies a value and parses it back into a JsonValue.
|
||||
*/
|
||||
export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => {
|
||||
try {
|
||||
const json = JSON.stringify(input, queryKeyJsonReplacer)
|
||||
if (json === undefined) {
|
||||
return undefined
|
||||
}
|
||||
return JSON.parse(json) as JsonValue
|
||||
} catch {
|
||||
return undefined
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Detects plain objects (including objects with a null prototype).
|
||||
*/
|
||||
const isPlainObject = (value: unknown): value is Record<string, unknown> => {
|
||||
if (value === null || typeof value !== "object") {
|
||||
return false
|
||||
}
|
||||
const prototype = Object.getPrototypeOf(value as object)
|
||||
return prototype === Object.prototype || prototype === null
|
||||
}
|
||||
|
||||
/**
|
||||
* Turns URLSearchParams into a sorted JSON object for deterministic keys.
|
||||
*/
|
||||
const serializeSearchParams = (params: URLSearchParams): JsonValue => {
|
||||
const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b))
|
||||
const result: Record<string, JsonValue> = {}
|
||||
|
||||
for (const [key, value] of entries) {
|
||||
const existing = result[key]
|
||||
if (existing === undefined) {
|
||||
result[key] = value
|
||||
continue
|
||||
}
|
||||
|
||||
if (Array.isArray(existing)) {
|
||||
;(existing as string[]).push(value)
|
||||
} else {
|
||||
result[key] = [existing, value]
|
||||
}
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalizes any accepted value into a JSON-friendly shape for query keys.
|
||||
*/
|
||||
export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => {
|
||||
if (value === null) {
|
||||
return null
|
||||
}
|
||||
|
||||
if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
|
||||
return value
|
||||
}
|
||||
|
||||
if (value === undefined || typeof value === "function" || typeof value === "symbol") {
|
||||
return undefined
|
||||
}
|
||||
|
||||
if (typeof value === "bigint") {
|
||||
return value.toString()
|
||||
}
|
||||
|
||||
if (value instanceof Date) {
|
||||
return value.toISOString()
|
||||
}
|
||||
|
||||
if (Array.isArray(value)) {
|
||||
return stringifyToJsonValue(value)
|
||||
}
|
||||
|
||||
if (typeof URLSearchParams !== "undefined" && value instanceof URLSearchParams) {
|
||||
return serializeSearchParams(value)
|
||||
}
|
||||
|
||||
if (isPlainObject(value)) {
|
||||
return stringifyToJsonValue(value)
|
||||
}
|
||||
|
||||
return undefined
|
||||
}
|
||||
|
|
@ -4,6 +4,17 @@ import type { Config } from "./types.gen.js"
|
|||
|
||||
export type ServerSentEventsOptions<TData = unknown> = Omit<RequestInit, "method"> &
|
||||
Pick<Config, "method" | "responseTransformer" | "responseValidator"> & {
|
||||
/**
|
||||
* Fetch API implementation. You can use this option to provide a custom
|
||||
* fetch instance.
|
||||
*
|
||||
* @default globalThis.fetch
|
||||
*/
|
||||
fetch?: typeof fetch
|
||||
/**
|
||||
* Implementing clients can call request interceptors inside this hook.
|
||||
*/
|
||||
onRequest?: (url: string, init: RequestInit) => Promise<Request>
|
||||
/**
|
||||
* Callback invoked when a network or parsing error occurs during streaming.
|
||||
*
|
||||
|
|
@ -21,6 +32,7 @@ export type ServerSentEventsOptions<TData = unknown> = Omit<RequestInit, "method
|
|||
* @returns Nothing (void).
|
||||
*/
|
||||
onSseEvent?: (event: StreamEvent<TData>) => void
|
||||
serializedBody?: RequestInit["body"]
|
||||
/**
|
||||
* Default retry delay in milliseconds.
|
||||
*
|
||||
|
|
@ -64,6 +76,7 @@ export type ServerSentEventsResult<TData = unknown, TReturn = void, TNext = unkn
|
|||
}
|
||||
|
||||
export const createSseClient = <TData = unknown>({
|
||||
onRequest,
|
||||
onSseError,
|
||||
onSseEvent,
|
||||
responseTransformer,
|
||||
|
|
@ -99,7 +112,21 @@ export const createSseClient = <TData = unknown>({
|
|||
}
|
||||
|
||||
try {
|
||||
const response = await fetch(url, { ...options, headers, signal })
|
||||
const requestInit: RequestInit = {
|
||||
redirect: "follow",
|
||||
...options,
|
||||
body: options.serializedBody,
|
||||
headers,
|
||||
signal,
|
||||
}
|
||||
let request = new Request(url, requestInit)
|
||||
if (onRequest) {
|
||||
request = await onRequest(url, requestInit)
|
||||
}
|
||||
// fetch must be assigned here, otherwise it would throw the error:
|
||||
// TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation
|
||||
const _fetch = options.fetch ?? globalThis.fetch
|
||||
const response = await _fetch(request)
|
||||
|
||||
if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`)
|
||||
|
||||
|
|
|
|||
|
|
@ -3,24 +3,19 @@
|
|||
import type { Auth, AuthToken } from "./auth.gen.js"
|
||||
import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from "./bodySerializer.gen.js"
|
||||
|
||||
export interface Client<RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never> {
|
||||
export type HttpMethod = "connect" | "delete" | "get" | "head" | "options" | "patch" | "post" | "put" | "trace"
|
||||
|
||||
export type Client<RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never> = {
|
||||
/**
|
||||
* Returns the final request URL.
|
||||
*/
|
||||
buildUrl: BuildUrlFn
|
||||
connect: MethodFn
|
||||
delete: MethodFn
|
||||
get: MethodFn
|
||||
getConfig: () => Config
|
||||
head: MethodFn
|
||||
options: MethodFn
|
||||
patch: MethodFn
|
||||
post: MethodFn
|
||||
put: MethodFn
|
||||
request: RequestFn
|
||||
setConfig: (config: Config) => Config
|
||||
trace: MethodFn
|
||||
}
|
||||
} & {
|
||||
[K in HttpMethod]: MethodFn
|
||||
} & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } })
|
||||
|
||||
export interface Config {
|
||||
/**
|
||||
|
|
@ -47,7 +42,7 @@ export interface Config {
|
|||
*
|
||||
* {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more}
|
||||
*/
|
||||
method?: "CONNECT" | "DELETE" | "GET" | "HEAD" | "OPTIONS" | "PATCH" | "POST" | "PUT" | "TRACE"
|
||||
method?: Uppercase<HttpMethod>
|
||||
/**
|
||||
* A function for serializing request query parameters. By default, arrays
|
||||
* will be exploded in form style, objects will be exploded in deepObject
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
// This file is auto-generated by @hey-api/openapi-ts
|
||||
|
||||
import type { QuerySerializer } from "./bodySerializer.gen.js"
|
||||
import type { BodySerializer, QuerySerializer } from "./bodySerializer.gen.js"
|
||||
import {
|
||||
type ArraySeparatorStyle,
|
||||
serializeArrayParam,
|
||||
|
|
@ -107,3 +107,31 @@ export const getUrl = ({
|
|||
}
|
||||
return url
|
||||
}
|
||||
|
||||
export function getValidRequestBody(options: {
|
||||
body?: unknown
|
||||
bodySerializer?: BodySerializer | null
|
||||
serializedBody?: unknown
|
||||
}) {
|
||||
const hasBody = options.body !== undefined
|
||||
const isSerializedBody = hasBody && options.bodySerializer
|
||||
|
||||
if (isSerializedBody) {
|
||||
if ("serializedBody" in options) {
|
||||
const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ""
|
||||
|
||||
return hasSerializedBody ? options.serializedBody : null
|
||||
}
|
||||
|
||||
// not all clients implement a serializedBody property (i.e. client-axios)
|
||||
return options.body !== "" ? options.body : null
|
||||
}
|
||||
|
||||
// plain/text body
|
||||
if (hasBody) {
|
||||
return options.body
|
||||
}
|
||||
|
||||
// no body was provided
|
||||
return undefined
|
||||
}
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load diff
|
|
@ -1,5 +1,9 @@
|
|||
// This file is auto-generated by @hey-api/openapi-ts
|
||||
|
||||
export type ClientOptions = {
|
||||
baseUrl: `${string}://${string}` | (string & {})
|
||||
}
|
||||
|
||||
export type EventServerInstanceDisposed = {
|
||||
type: "server.instance.disposed"
|
||||
properties: {
|
||||
|
|
@ -622,22 +626,20 @@ export type EventTuiCommandExecute = {
|
|||
type: "tui.command.execute"
|
||||
properties: {
|
||||
command:
|
||||
| (
|
||||
| "session.list"
|
||||
| "session.new"
|
||||
| "session.share"
|
||||
| "session.interrupt"
|
||||
| "session.compact"
|
||||
| "session.page.up"
|
||||
| "session.page.down"
|
||||
| "session.half.page.up"
|
||||
| "session.half.page.down"
|
||||
| "session.first"
|
||||
| "session.last"
|
||||
| "prompt.clear"
|
||||
| "prompt.submit"
|
||||
| "agent.cycle"
|
||||
)
|
||||
| "session.list"
|
||||
| "session.new"
|
||||
| "session.share"
|
||||
| "session.interrupt"
|
||||
| "session.compact"
|
||||
| "session.page.up"
|
||||
| "session.page.down"
|
||||
| "session.half.page.up"
|
||||
| "session.half.page.down"
|
||||
| "session.first"
|
||||
| "session.last"
|
||||
| "prompt.clear"
|
||||
| "prompt.submit"
|
||||
| "agent.cycle"
|
||||
| string
|
||||
}
|
||||
}
|
||||
|
|
@ -977,7 +979,9 @@ export type AgentConfig = {
|
|||
permission?: {
|
||||
edit?: "ask" | "allow" | "deny"
|
||||
bash?:
|
||||
| ("ask" | "allow" | "deny")
|
||||
| "ask"
|
||||
| "allow"
|
||||
| "deny"
|
||||
| {
|
||||
[key: string]: "ask" | "allow" | "deny"
|
||||
}
|
||||
|
|
@ -993,12 +997,17 @@ export type AgentConfig = {
|
|||
[key: string]: boolean
|
||||
}
|
||||
| boolean
|
||||
| ("subagent" | "primary" | "all")
|
||||
| "subagent"
|
||||
| "primary"
|
||||
| "all"
|
||||
| string
|
||||
| number
|
||||
| {
|
||||
edit?: "ask" | "allow" | "deny"
|
||||
bash?:
|
||||
| ("ask" | "allow" | "deny")
|
||||
| "ask"
|
||||
| "allow"
|
||||
| "deny"
|
||||
| {
|
||||
[key: string]: "ask" | "allow" | "deny"
|
||||
}
|
||||
|
|
@ -1074,7 +1083,7 @@ export type ProviderConfig = {
|
|||
* Timeout in milliseconds for requests to this provider. Default is 300000 (5 minutes). Set to false to disable timeout.
|
||||
*/
|
||||
timeout?: number | false
|
||||
[key: string]: unknown | string | boolean | (number | false) | undefined
|
||||
[key: string]: unknown | string | boolean | number | false | undefined
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -1302,7 +1311,9 @@ export type Config = {
|
|||
permission?: {
|
||||
edit?: "ask" | "allow" | "deny"
|
||||
bash?:
|
||||
| ("ask" | "allow" | "deny")
|
||||
| "ask"
|
||||
| "allow"
|
||||
| "deny"
|
||||
| {
|
||||
[key: string]: "ask" | "allow" | "deny"
|
||||
}
|
||||
|
|
@ -1760,12 +1771,12 @@ export type PtyCreateResponse = PtyCreateResponses[keyof PtyCreateResponses]
|
|||
export type PtyRemoveData = {
|
||||
body?: never
|
||||
path: {
|
||||
id: string
|
||||
ptyID: string
|
||||
}
|
||||
query?: {
|
||||
directory?: string
|
||||
}
|
||||
url: "/pty/{id}"
|
||||
url: "/pty/{ptyID}"
|
||||
}
|
||||
|
||||
export type PtyRemoveErrors = {
|
||||
|
|
@ -1789,12 +1800,12 @@ export type PtyRemoveResponse = PtyRemoveResponses[keyof PtyRemoveResponses]
|
|||
export type PtyGetData = {
|
||||
body?: never
|
||||
path: {
|
||||
id: string
|
||||
ptyID: string
|
||||
}
|
||||
query?: {
|
||||
directory?: string
|
||||
}
|
||||
url: "/pty/{id}"
|
||||
url: "/pty/{ptyID}"
|
||||
}
|
||||
|
||||
export type PtyGetErrors = {
|
||||
|
|
@ -1824,12 +1835,12 @@ export type PtyUpdateData = {
|
|||
}
|
||||
}
|
||||
path: {
|
||||
id: string
|
||||
ptyID: string
|
||||
}
|
||||
query?: {
|
||||
directory?: string
|
||||
}
|
||||
url: "/pty/{id}"
|
||||
url: "/pty/{ptyID}"
|
||||
}
|
||||
|
||||
export type PtyUpdateErrors = {
|
||||
|
|
@ -1853,12 +1864,12 @@ export type PtyUpdateResponse = PtyUpdateResponses[keyof PtyUpdateResponses]
|
|||
export type PtyConnectData = {
|
||||
body?: never
|
||||
path: {
|
||||
id: string
|
||||
ptyID: string
|
||||
}
|
||||
query?: {
|
||||
directory?: string
|
||||
}
|
||||
url: "/pty/{id}/connect"
|
||||
url: "/pty/{ptyID}/connect"
|
||||
}
|
||||
|
||||
export type PtyConnectErrors = {
|
||||
|
|
@ -2114,12 +2125,12 @@ export type SessionStatusResponse = SessionStatusResponses[keyof SessionStatusRe
|
|||
export type SessionDeleteData = {
|
||||
body?: never
|
||||
path: {
|
||||
id: string
|
||||
sessionID: string
|
||||
}
|
||||
query?: {
|
||||
directory?: string
|
||||
}
|
||||
url: "/session/{id}"
|
||||
url: "/session/{sessionID}"
|
||||
}
|
||||
|
||||
export type SessionDeleteErrors = {
|
||||
|
|
@ -2147,12 +2158,12 @@ export type SessionDeleteResponse = SessionDeleteResponses[keyof SessionDeleteRe
|
|||
export type SessionGetData = {
|
||||
body?: never
|
||||
path: {
|
||||
id: string
|
||||
sessionID: string
|
||||
}
|
||||
query?: {
|
||||
directory?: string
|
||||
}
|
||||
url: "/session/{id}"
|
||||
url: "/session/{sessionID}"
|
||||
}
|
||||
|
||||
export type SessionGetErrors = {
|
||||
|
|
@ -2182,12 +2193,12 @@ export type SessionUpdateData = {
|
|||
title?: string
|
||||
}
|
||||
path: {
|
||||
id: string
|
||||
sessionID: string
|
||||
}
|
||||
query?: {
|
||||
directory?: string
|
||||
}
|
||||
url: "/session/{id}"
|
||||
url: "/session/{sessionID}"
|
||||
}
|
||||
|
||||
export type SessionUpdateErrors = {
|
||||
|
|
@ -2215,12 +2226,12 @@ export type SessionUpdateResponse = SessionUpdateResponses[keyof SessionUpdateRe
|
|||
export type SessionChildrenData = {
|
||||
body?: never
|
||||
path: {
|
||||
id: string
|
||||
sessionID: string
|
||||
}
|
||||
query?: {
|
||||
directory?: string
|
||||
}
|
||||
url: "/session/{id}/children"
|
||||
url: "/session/{sessionID}/children"
|
||||
}
|
||||
|
||||
export type SessionChildrenErrors = {
|
||||
|
|
@ -2251,12 +2262,12 @@ export type SessionTodoData = {
|
|||
/**
|
||||
* Session ID
|
||||
*/
|
||||
id: string
|
||||
sessionID: string
|
||||
}
|
||||
query?: {
|
||||
directory?: string
|
||||
}
|
||||
url: "/session/{id}/todo"
|
||||
url: "/session/{sessionID}/todo"
|
||||
}
|
||||
|
||||
export type SessionTodoErrors = {
|
||||
|
|
@ -2291,12 +2302,12 @@ export type SessionInitData = {
|
|||
/**
|
||||
* Session ID
|
||||
*/
|
||||
id: string
|
||||
sessionID: string
|
||||
}
|
||||
query?: {
|
||||
directory?: string
|
||||
}
|
||||
url: "/session/{id}/init"
|
||||
url: "/session/{sessionID}/init"
|
||||
}
|
||||
|
||||
export type SessionInitErrors = {
|
||||
|
|
@ -2326,12 +2337,12 @@ export type SessionForkData = {
|
|||
messageID?: string
|
||||
}
|
||||
path: {
|
||||
id: string
|
||||
sessionID: string
|
||||
}
|
||||
query?: {
|
||||
directory?: string
|
||||
}
|
||||
url: "/session/{id}/fork"
|
||||
url: "/session/{sessionID}/fork"
|
||||
}
|
||||
|
||||
export type SessionForkResponses = {
|
||||
|
|
@ -2346,12 +2357,12 @@ export type SessionForkResponse = SessionForkResponses[keyof SessionForkResponse
|
|||
export type SessionAbortData = {
|
||||
body?: never
|
||||
path: {
|
||||
id: string
|
||||
sessionID: string
|
||||
}
|
||||
query?: {
|
||||
directory?: string
|
||||
}
|
||||
url: "/session/{id}/abort"
|
||||
url: "/session/{sessionID}/abort"
|
||||
}
|
||||
|
||||
export type SessionAbortErrors = {
|
||||
|
|
@ -2379,12 +2390,12 @@ export type SessionAbortResponse = SessionAbortResponses[keyof SessionAbortRespo
|
|||
export type SessionUnshareData = {
|
||||
body?: never
|
||||
path: {
|
||||
id: string
|
||||
sessionID: string
|
||||
}
|
||||
query?: {
|
||||
directory?: string
|
||||
}
|
||||
url: "/session/{id}/share"
|
||||
url: "/session/{sessionID}/share"
|
||||
}
|
||||
|
||||
export type SessionUnshareErrors = {
|
||||
|
|
@ -2412,12 +2423,12 @@ export type SessionUnshareResponse = SessionUnshareResponses[keyof SessionUnshar
|
|||
export type SessionShareData = {
|
||||
body?: never
|
||||
path: {
|
||||
id: string
|
||||
sessionID: string
|
||||
}
|
||||
query?: {
|
||||
directory?: string
|
||||
}
|
||||
url: "/session/{id}/share"
|
||||
url: "/session/{sessionID}/share"
|
||||
}
|
||||
|
||||
export type SessionShareErrors = {
|
||||
|
|
@ -2448,13 +2459,13 @@ export type SessionDiffData = {
|
|||
/**
|
||||
* Session ID
|
||||
*/
|
||||
id: string
|
||||
sessionID: string
|
||||
}
|
||||
query?: {
|
||||
directory?: string
|
||||
messageID?: string
|
||||
}
|
||||
url: "/session/{id}/diff"
|
||||
url: "/session/{sessionID}/diff"
|
||||
}
|
||||
|
||||
export type SessionDiffErrors = {
|
||||
|
|
@ -2488,12 +2499,12 @@ export type SessionSummarizeData = {
|
|||
/**
|
||||
* Session ID
|
||||
*/
|
||||
id: string
|
||||
sessionID: string
|
||||
}
|
||||
query?: {
|
||||
directory?: string
|
||||
}
|
||||
url: "/session/{id}/summarize"
|
||||
url: "/session/{sessionID}/summarize"
|
||||
}
|
||||
|
||||
export type SessionSummarizeErrors = {
|
||||
|
|
@ -2524,13 +2535,13 @@ export type SessionMessagesData = {
|
|||
/**
|
||||
* Session ID
|
||||
*/
|
||||
id: string
|
||||
sessionID: string
|
||||
}
|
||||
query?: {
|
||||
directory?: string
|
||||
limit?: number
|
||||
}
|
||||
url: "/session/{id}/message"
|
||||
url: "/session/{sessionID}/message"
|
||||
}
|
||||
|
||||
export type SessionMessagesErrors = {
|
||||
|
|
@ -2577,12 +2588,12 @@ export type SessionPromptData = {
|
|||
/**
|
||||
* Session ID
|
||||
*/
|
||||
id: string
|
||||
sessionID: string
|
||||
}
|
||||
query?: {
|
||||
directory?: string
|
||||
}
|
||||
url: "/session/{id}/message"
|
||||
url: "/session/{sessionID}/message"
|
||||
}
|
||||
|
||||
export type SessionPromptErrors = {
|
||||
|
|
@ -2616,7 +2627,7 @@ export type SessionMessageData = {
|
|||
/**
|
||||
* Session ID
|
||||
*/
|
||||
id: string
|
||||
sessionID: string
|
||||
/**
|
||||
* Message ID
|
||||
*/
|
||||
|
|
@ -2625,7 +2636,7 @@ export type SessionMessageData = {
|
|||
query?: {
|
||||
directory?: string
|
||||
}
|
||||
url: "/session/{id}/message/{messageID}"
|
||||
url: "/session/{sessionID}/message/{messageID}"
|
||||
}
|
||||
|
||||
export type SessionMessageErrors = {
|
||||
|
|
@ -2672,12 +2683,12 @@ export type SessionPromptAsyncData = {
|
|||
/**
|
||||
* Session ID
|
||||
*/
|
||||
id: string
|
||||
sessionID: string
|
||||
}
|
||||
query?: {
|
||||
directory?: string
|
||||
}
|
||||
url: "/session/{id}/prompt_async"
|
||||
url: "/session/{sessionID}/prompt_async"
|
||||
}
|
||||
|
||||
export type SessionPromptAsyncErrors = {
|
||||
|
|
@ -2714,12 +2725,12 @@ export type SessionCommandData = {
|
|||
/**
|
||||
* Session ID
|
||||
*/
|
||||
id: string
|
||||
sessionID: string
|
||||
}
|
||||
query?: {
|
||||
directory?: string
|
||||
}
|
||||
url: "/session/{id}/command"
|
||||
url: "/session/{sessionID}/command"
|
||||
}
|
||||
|
||||
export type SessionCommandErrors = {
|
||||
|
|
@ -2760,12 +2771,12 @@ export type SessionShellData = {
|
|||
/**
|
||||
* Session ID
|
||||
*/
|
||||
id: string
|
||||
sessionID: string
|
||||
}
|
||||
query?: {
|
||||
directory?: string
|
||||
}
|
||||
url: "/session/{id}/shell"
|
||||
url: "/session/{sessionID}/shell"
|
||||
}
|
||||
|
||||
export type SessionShellErrors = {
|
||||
|
|
@ -2796,12 +2807,12 @@ export type SessionRevertData = {
|
|||
partID?: string
|
||||
}
|
||||
path: {
|
||||
id: string
|
||||
sessionID: string
|
||||
}
|
||||
query?: {
|
||||
directory?: string
|
||||
}
|
||||
url: "/session/{id}/revert"
|
||||
url: "/session/{sessionID}/revert"
|
||||
}
|
||||
|
||||
export type SessionRevertErrors = {
|
||||
|
|
@ -2829,12 +2840,12 @@ export type SessionRevertResponse = SessionRevertResponses[keyof SessionRevertRe
|
|||
export type SessionUnrevertData = {
|
||||
body?: never
|
||||
path: {
|
||||
id: string
|
||||
sessionID: string
|
||||
}
|
||||
query?: {
|
||||
directory?: string
|
||||
}
|
||||
url: "/session/{id}/unrevert"
|
||||
url: "/session/{sessionID}/unrevert"
|
||||
}
|
||||
|
||||
export type SessionUnrevertErrors = {
|
||||
|
|
@ -2859,21 +2870,21 @@ export type SessionUnrevertResponses = {
|
|||
|
||||
export type SessionUnrevertResponse = SessionUnrevertResponses[keyof SessionUnrevertResponses]
|
||||
|
||||
export type PostSessionIdPermissionsPermissionIdData = {
|
||||
export type PermissionRespondData = {
|
||||
body?: {
|
||||
response: "once" | "always" | "reject"
|
||||
}
|
||||
path: {
|
||||
id: string
|
||||
sessionID: string
|
||||
permissionID: string
|
||||
}
|
||||
query?: {
|
||||
directory?: string
|
||||
}
|
||||
url: "/session/{id}/permissions/{permissionID}"
|
||||
url: "/session/{sessionID}/permissions/{permissionID}"
|
||||
}
|
||||
|
||||
export type PostSessionIdPermissionsPermissionIdErrors = {
|
||||
export type PermissionRespondErrors = {
|
||||
/**
|
||||
* Bad request
|
||||
*/
|
||||
|
|
@ -2884,18 +2895,16 @@ export type PostSessionIdPermissionsPermissionIdErrors = {
|
|||
404: NotFoundError
|
||||
}
|
||||
|
||||
export type PostSessionIdPermissionsPermissionIdError =
|
||||
PostSessionIdPermissionsPermissionIdErrors[keyof PostSessionIdPermissionsPermissionIdErrors]
|
||||
export type PermissionRespondError = PermissionRespondErrors[keyof PermissionRespondErrors]
|
||||
|
||||
export type PostSessionIdPermissionsPermissionIdResponses = {
|
||||
export type PermissionRespondResponses = {
|
||||
/**
|
||||
* Permission processed successfully
|
||||
*/
|
||||
200: boolean
|
||||
}
|
||||
|
||||
export type PostSessionIdPermissionsPermissionIdResponse =
|
||||
PostSessionIdPermissionsPermissionIdResponses[keyof PostSessionIdPermissionsPermissionIdResponses]
|
||||
export type PermissionRespondResponse = PermissionRespondResponses[keyof PermissionRespondResponses]
|
||||
|
||||
export type CommandListData = {
|
||||
body?: never
|
||||
|
|
@ -3041,12 +3050,12 @@ export type ProviderOauthAuthorizeData = {
|
|||
/**
|
||||
* Provider ID
|
||||
*/
|
||||
id: string
|
||||
providerID: string
|
||||
}
|
||||
query?: {
|
||||
directory?: string
|
||||
}
|
||||
url: "/provider/{id}/oauth/authorize"
|
||||
url: "/provider/{providerID}/oauth/authorize"
|
||||
}
|
||||
|
||||
export type ProviderOauthAuthorizeErrors = {
|
||||
|
|
@ -3082,12 +3091,12 @@ export type ProviderOauthCallbackData = {
|
|||
/**
|
||||
* Provider ID
|
||||
*/
|
||||
id: string
|
||||
providerID: string
|
||||
}
|
||||
query?: {
|
||||
directory?: string
|
||||
}
|
||||
url: "/provider/{id}/oauth/callback"
|
||||
url: "/provider/{providerID}/oauth/callback"
|
||||
}
|
||||
|
||||
export type ProviderOauthCallbackErrors = {
|
||||
|
|
@ -3791,12 +3800,12 @@ export type TuiControlResponseResponse = TuiControlResponseResponses[keyof TuiCo
|
|||
export type AuthSetData = {
|
||||
body?: Auth
|
||||
path: {
|
||||
id: string
|
||||
providerID: string
|
||||
}
|
||||
query?: {
|
||||
directory?: string
|
||||
}
|
||||
url: "/auth/{id}"
|
||||
url: "/auth/{providerID}"
|
||||
}
|
||||
|
||||
export type AuthSetErrors = {
|
||||
|
|
@ -3834,7 +3843,3 @@ export type EventSubscribeResponses = {
|
|||
}
|
||||
|
||||
export type EventSubscribeResponse = EventSubscribeResponses[keyof EventSubscribeResponses]
|
||||
|
||||
export type ClientOptions = {
|
||||
baseUrl: `${string}://${string}` | (string & {})
|
||||
}
|
||||
|
|
|
|||
30
packages/sdk/js/src/v2/client.ts
Normal file
30
packages/sdk/js/src/v2/client.ts
Normal file
|
|
@ -0,0 +1,30 @@
|
|||
export * from "./gen/types.gen.js"
|
||||
|
||||
import { createClient } from "./gen/client/client.gen.js"
|
||||
import { type Config } from "./gen/client/types.gen.js"
|
||||
import { OpencodeClient } from "./gen/sdk.gen.js"
|
||||
export { type Config as OpencodeClientConfig, OpencodeClient }
|
||||
|
||||
export function createOpencodeClient(config?: Config & { directory?: string }) {
|
||||
if (!config?.fetch) {
|
||||
const customFetch: any = (req: any) => {
|
||||
// @ts-ignore
|
||||
req.timeout = false
|
||||
return fetch(req)
|
||||
}
|
||||
config = {
|
||||
...config,
|
||||
fetch: customFetch,
|
||||
}
|
||||
}
|
||||
|
||||
if (config?.directory) {
|
||||
config.headers = {
|
||||
...config.headers,
|
||||
"x-opencode-directory": config.directory,
|
||||
}
|
||||
}
|
||||
|
||||
const client = createClient(config)
|
||||
return new OpencodeClient({ client })
|
||||
}
|
||||
16
packages/sdk/js/src/v2/gen/client.gen.ts
Normal file
16
packages/sdk/js/src/v2/gen/client.gen.ts
Normal file
|
|
@ -0,0 +1,16 @@
|
|||
// This file is auto-generated by @hey-api/openapi-ts
|
||||
|
||||
import { type ClientOptions, type Config, createClient, createConfig } from './client/index.js';
|
||||
import type { ClientOptions as ClientOptions2 } from './types.gen.js';
|
||||
|
||||
/**
|
||||
* The `createClientConfig()` function will be called on client initialization
|
||||
* and the returned object will become the client's initial configuration.
|
||||
*
|
||||
* You may want to initialize your client this way instead of calling
|
||||
* `setConfig()`. This is useful for example if you're using Next.js
|
||||
* to ensure your client always has the correct values.
|
||||
*/
|
||||
export type CreateClientConfig<T extends ClientOptions = ClientOptions2> = (override?: Config<ClientOptions & T>) => Config<Required<ClientOptions> & T>;
|
||||
|
||||
export const client = createClient(createConfig<ClientOptions2>({ baseUrl: 'http://localhost:4096' }));
|
||||
301
packages/sdk/js/src/v2/gen/client/client.gen.ts
Normal file
301
packages/sdk/js/src/v2/gen/client/client.gen.ts
Normal file
|
|
@ -0,0 +1,301 @@
|
|||
// This file is auto-generated by @hey-api/openapi-ts
|
||||
|
||||
import { createSseClient } from '../core/serverSentEvents.gen.js';
|
||||
import type { HttpMethod } from '../core/types.gen.js';
|
||||
import { getValidRequestBody } from '../core/utils.gen.js';
|
||||
import type {
|
||||
Client,
|
||||
Config,
|
||||
RequestOptions,
|
||||
ResolvedRequestOptions,
|
||||
} from './types.gen.js';
|
||||
import {
|
||||
buildUrl,
|
||||
createConfig,
|
||||
createInterceptors,
|
||||
getParseAs,
|
||||
mergeConfigs,
|
||||
mergeHeaders,
|
||||
setAuthParams,
|
||||
} from './utils.gen.js';
|
||||
|
||||
type ReqInit = Omit<RequestInit, 'body' | 'headers'> & {
|
||||
body?: any;
|
||||
headers: ReturnType<typeof mergeHeaders>;
|
||||
};
|
||||
|
||||
export const createClient = (config: Config = {}): Client => {
|
||||
let _config = mergeConfigs(createConfig(), config);
|
||||
|
||||
const getConfig = (): Config => ({ ..._config });
|
||||
|
||||
const setConfig = (config: Config): Config => {
|
||||
_config = mergeConfigs(_config, config);
|
||||
return getConfig();
|
||||
};
|
||||
|
||||
const interceptors = createInterceptors<
|
||||
Request,
|
||||
Response,
|
||||
unknown,
|
||||
ResolvedRequestOptions
|
||||
>();
|
||||
|
||||
const beforeRequest = async (options: RequestOptions) => {
|
||||
const opts = {
|
||||
..._config,
|
||||
...options,
|
||||
fetch: options.fetch ?? _config.fetch ?? globalThis.fetch,
|
||||
headers: mergeHeaders(_config.headers, options.headers),
|
||||
serializedBody: undefined,
|
||||
};
|
||||
|
||||
if (opts.security) {
|
||||
await setAuthParams({
|
||||
...opts,
|
||||
security: opts.security,
|
||||
});
|
||||
}
|
||||
|
||||
if (opts.requestValidator) {
|
||||
await opts.requestValidator(opts);
|
||||
}
|
||||
|
||||
if (opts.body !== undefined && opts.bodySerializer) {
|
||||
opts.serializedBody = opts.bodySerializer(opts.body);
|
||||
}
|
||||
|
||||
// remove Content-Type header if body is empty to avoid sending invalid requests
|
||||
if (opts.body === undefined || opts.serializedBody === '') {
|
||||
opts.headers.delete('Content-Type');
|
||||
}
|
||||
|
||||
const url = buildUrl(opts);
|
||||
|
||||
return { opts, url };
|
||||
};
|
||||
|
||||
const request: Client['request'] = async (options) => {
|
||||
// @ts-expect-error
|
||||
const { opts, url } = await beforeRequest(options);
|
||||
const requestInit: ReqInit = {
|
||||
redirect: 'follow',
|
||||
...opts,
|
||||
body: getValidRequestBody(opts),
|
||||
};
|
||||
|
||||
let request = new Request(url, requestInit);
|
||||
|
||||
for (const fn of interceptors.request.fns) {
|
||||
if (fn) {
|
||||
request = await fn(request, opts);
|
||||
}
|
||||
}
|
||||
|
||||
// fetch must be assigned here, otherwise it would throw the error:
|
||||
// TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation
|
||||
const _fetch = opts.fetch!;
|
||||
let response: Response;
|
||||
|
||||
try {
|
||||
response = await _fetch(request);
|
||||
} catch (error) {
|
||||
// Handle fetch exceptions (AbortError, network errors, etc.)
|
||||
let finalError = error;
|
||||
|
||||
for (const fn of interceptors.error.fns) {
|
||||
if (fn) {
|
||||
finalError = (await fn(
|
||||
error,
|
||||
undefined as any,
|
||||
request,
|
||||
opts,
|
||||
)) as unknown;
|
||||
}
|
||||
}
|
||||
|
||||
finalError = finalError || ({} as unknown);
|
||||
|
||||
if (opts.throwOnError) {
|
||||
throw finalError;
|
||||
}
|
||||
|
||||
// Return error response
|
||||
return opts.responseStyle === 'data'
|
||||
? undefined
|
||||
: {
|
||||
error: finalError,
|
||||
request,
|
||||
response: undefined as any,
|
||||
};
|
||||
}
|
||||
|
||||
for (const fn of interceptors.response.fns) {
|
||||
if (fn) {
|
||||
response = await fn(response, request, opts);
|
||||
}
|
||||
}
|
||||
|
||||
const result = {
|
||||
request,
|
||||
response,
|
||||
};
|
||||
|
||||
if (response.ok) {
|
||||
const parseAs =
|
||||
(opts.parseAs === 'auto'
|
||||
? getParseAs(response.headers.get('Content-Type'))
|
||||
: opts.parseAs) ?? 'json';
|
||||
|
||||
if (
|
||||
response.status === 204 ||
|
||||
response.headers.get('Content-Length') === '0'
|
||||
) {
|
||||
let emptyData: any;
|
||||
switch (parseAs) {
|
||||
case 'arrayBuffer':
|
||||
case 'blob':
|
||||
case 'text':
|
||||
emptyData = await response[parseAs]();
|
||||
break;
|
||||
case 'formData':
|
||||
emptyData = new FormData();
|
||||
break;
|
||||
case 'stream':
|
||||
emptyData = response.body;
|
||||
break;
|
||||
case 'json':
|
||||
default:
|
||||
emptyData = {};
|
||||
break;
|
||||
}
|
||||
return opts.responseStyle === 'data'
|
||||
? emptyData
|
||||
: {
|
||||
data: emptyData,
|
||||
...result,
|
||||
};
|
||||
}
|
||||
|
||||
let data: any;
|
||||
switch (parseAs) {
|
||||
case 'arrayBuffer':
|
||||
case 'blob':
|
||||
case 'formData':
|
||||
case 'json':
|
||||
case 'text':
|
||||
data = await response[parseAs]();
|
||||
break;
|
||||
case 'stream':
|
||||
return opts.responseStyle === 'data'
|
||||
? response.body
|
||||
: {
|
||||
data: response.body,
|
||||
...result,
|
||||
};
|
||||
}
|
||||
|
||||
if (parseAs === 'json') {
|
||||
if (opts.responseValidator) {
|
||||
await opts.responseValidator(data);
|
||||
}
|
||||
|
||||
if (opts.responseTransformer) {
|
||||
data = await opts.responseTransformer(data);
|
||||
}
|
||||
}
|
||||
|
||||
return opts.responseStyle === 'data'
|
||||
? data
|
||||
: {
|
||||
data,
|
||||
...result,
|
||||
};
|
||||
}
|
||||
|
||||
const textError = await response.text();
|
||||
let jsonError: unknown;
|
||||
|
||||
try {
|
||||
jsonError = JSON.parse(textError);
|
||||
} catch {
|
||||
// noop
|
||||
}
|
||||
|
||||
const error = jsonError ?? textError;
|
||||
let finalError = error;
|
||||
|
||||
for (const fn of interceptors.error.fns) {
|
||||
if (fn) {
|
||||
finalError = (await fn(error, response, request, opts)) as string;
|
||||
}
|
||||
}
|
||||
|
||||
finalError = finalError || ({} as string);
|
||||
|
||||
if (opts.throwOnError) {
|
||||
throw finalError;
|
||||
}
|
||||
|
||||
// TODO: we probably want to return error and improve types
|
||||
return opts.responseStyle === 'data'
|
||||
? undefined
|
||||
: {
|
||||
error: finalError,
|
||||
...result,
|
||||
};
|
||||
};
|
||||
|
||||
const makeMethodFn =
|
||||
(method: Uppercase<HttpMethod>) => (options: RequestOptions) =>
|
||||
request({ ...options, method });
|
||||
|
||||
const makeSseFn =
|
||||
(method: Uppercase<HttpMethod>) => async (options: RequestOptions) => {
|
||||
const { opts, url } = await beforeRequest(options);
|
||||
return createSseClient({
|
||||
...opts,
|
||||
body: opts.body as BodyInit | null | undefined,
|
||||
headers: opts.headers as unknown as Record<string, string>,
|
||||
method,
|
||||
onRequest: async (url, init) => {
|
||||
let request = new Request(url, init);
|
||||
for (const fn of interceptors.request.fns) {
|
||||
if (fn) {
|
||||
request = await fn(request, opts);
|
||||
}
|
||||
}
|
||||
return request;
|
||||
},
|
||||
url,
|
||||
});
|
||||
};
|
||||
|
||||
return {
|
||||
buildUrl,
|
||||
connect: makeMethodFn('CONNECT'),
|
||||
delete: makeMethodFn('DELETE'),
|
||||
get: makeMethodFn('GET'),
|
||||
getConfig,
|
||||
head: makeMethodFn('HEAD'),
|
||||
interceptors,
|
||||
options: makeMethodFn('OPTIONS'),
|
||||
patch: makeMethodFn('PATCH'),
|
||||
post: makeMethodFn('POST'),
|
||||
put: makeMethodFn('PUT'),
|
||||
request,
|
||||
setConfig,
|
||||
sse: {
|
||||
connect: makeSseFn('CONNECT'),
|
||||
delete: makeSseFn('DELETE'),
|
||||
get: makeSseFn('GET'),
|
||||
head: makeSseFn('HEAD'),
|
||||
options: makeSseFn('OPTIONS'),
|
||||
patch: makeSseFn('PATCH'),
|
||||
post: makeSseFn('POST'),
|
||||
put: makeSseFn('PUT'),
|
||||
trace: makeSseFn('TRACE'),
|
||||
},
|
||||
trace: makeMethodFn('TRACE'),
|
||||
} as Client;
|
||||
};
|
||||
25
packages/sdk/js/src/v2/gen/client/index.ts
Normal file
25
packages/sdk/js/src/v2/gen/client/index.ts
Normal file
|
|
@ -0,0 +1,25 @@
|
|||
// This file is auto-generated by @hey-api/openapi-ts
|
||||
|
||||
export type { Auth } from '../core/auth.gen.js';
|
||||
export type { QuerySerializerOptions } from '../core/bodySerializer.gen.js';
|
||||
export {
|
||||
formDataBodySerializer,
|
||||
jsonBodySerializer,
|
||||
urlSearchParamsBodySerializer,
|
||||
} from '../core/bodySerializer.gen.js';
|
||||
export { buildClientParams } from '../core/params.gen.js';
|
||||
export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen.js';
|
||||
export { createClient } from './client.gen.js';
|
||||
export type {
|
||||
Client,
|
||||
ClientOptions,
|
||||
Config,
|
||||
CreateClientConfig,
|
||||
Options,
|
||||
RequestOptions,
|
||||
RequestResult,
|
||||
ResolvedRequestOptions,
|
||||
ResponseStyle,
|
||||
TDataShape,
|
||||
} from './types.gen.js';
|
||||
export { createConfig, mergeHeaders } from './utils.gen.js';
|
||||
241
packages/sdk/js/src/v2/gen/client/types.gen.ts
Normal file
241
packages/sdk/js/src/v2/gen/client/types.gen.ts
Normal file
|
|
@ -0,0 +1,241 @@
|
|||
// This file is auto-generated by @hey-api/openapi-ts
|
||||
|
||||
import type { Auth } from '../core/auth.gen.js';
|
||||
import type {
|
||||
ServerSentEventsOptions,
|
||||
ServerSentEventsResult,
|
||||
} from '../core/serverSentEvents.gen.js';
|
||||
import type {
|
||||
Client as CoreClient,
|
||||
Config as CoreConfig,
|
||||
} from '../core/types.gen.js';
|
||||
import type { Middleware } from './utils.gen.js';
|
||||
|
||||
export type ResponseStyle = 'data' | 'fields';
|
||||
|
||||
export interface Config<T extends ClientOptions = ClientOptions>
|
||||
extends Omit<RequestInit, 'body' | 'headers' | 'method'>,
|
||||
CoreConfig {
|
||||
/**
|
||||
* Base URL for all requests made by this client.
|
||||
*/
|
||||
baseUrl?: T['baseUrl'];
|
||||
/**
|
||||
* Fetch API implementation. You can use this option to provide a custom
|
||||
* fetch instance.
|
||||
*
|
||||
* @default globalThis.fetch
|
||||
*/
|
||||
fetch?: typeof fetch;
|
||||
/**
|
||||
* Please don't use the Fetch client for Next.js applications. The `next`
|
||||
* options won't have any effect.
|
||||
*
|
||||
* Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead.
|
||||
*/
|
||||
next?: never;
|
||||
/**
|
||||
* Return the response data parsed in a specified format. By default, `auto`
|
||||
* will infer the appropriate method from the `Content-Type` response header.
|
||||
* You can override this behavior with any of the {@link Body} methods.
|
||||
* Select `stream` if you don't want to parse response data at all.
|
||||
*
|
||||
* @default 'auto'
|
||||
*/
|
||||
parseAs?:
|
||||
| 'arrayBuffer'
|
||||
| 'auto'
|
||||
| 'blob'
|
||||
| 'formData'
|
||||
| 'json'
|
||||
| 'stream'
|
||||
| 'text';
|
||||
/**
|
||||
* Should we return only data or multiple fields (data, error, response, etc.)?
|
||||
*
|
||||
* @default 'fields'
|
||||
*/
|
||||
responseStyle?: ResponseStyle;
|
||||
/**
|
||||
* Throw an error instead of returning it in the response?
|
||||
*
|
||||
* @default false
|
||||
*/
|
||||
throwOnError?: T['throwOnError'];
|
||||
}
|
||||
|
||||
export interface RequestOptions<
|
||||
TData = unknown,
|
||||
TResponseStyle extends ResponseStyle = 'fields',
|
||||
ThrowOnError extends boolean = boolean,
|
||||
Url extends string = string,
|
||||
> extends Config<{
|
||||
responseStyle: TResponseStyle;
|
||||
throwOnError: ThrowOnError;
|
||||
}>,
|
||||
Pick<
|
||||
ServerSentEventsOptions<TData>,
|
||||
| 'onSseError'
|
||||
| 'onSseEvent'
|
||||
| 'sseDefaultRetryDelay'
|
||||
| 'sseMaxRetryAttempts'
|
||||
| 'sseMaxRetryDelay'
|
||||
> {
|
||||
/**
|
||||
* Any body that you want to add to your request.
|
||||
*
|
||||
* {@link https://developer.mozilla.org/docs/Web/API/fetch#body}
|
||||
*/
|
||||
body?: unknown;
|
||||
path?: Record<string, unknown>;
|
||||
query?: Record<string, unknown>;
|
||||
/**
|
||||
* Security mechanism(s) to use for the request.
|
||||
*/
|
||||
security?: ReadonlyArray<Auth>;
|
||||
url: Url;
|
||||
}
|
||||
|
||||
export interface ResolvedRequestOptions<
|
||||
TResponseStyle extends ResponseStyle = 'fields',
|
||||
ThrowOnError extends boolean = boolean,
|
||||
Url extends string = string,
|
||||
> extends RequestOptions<unknown, TResponseStyle, ThrowOnError, Url> {
|
||||
serializedBody?: string;
|
||||
}
|
||||
|
||||
export type RequestResult<
|
||||
TData = unknown,
|
||||
TError = unknown,
|
||||
ThrowOnError extends boolean = boolean,
|
||||
TResponseStyle extends ResponseStyle = 'fields',
|
||||
> = ThrowOnError extends true
|
||||
? Promise<
|
||||
TResponseStyle extends 'data'
|
||||
? TData extends Record<string, unknown>
|
||||
? TData[keyof TData]
|
||||
: TData
|
||||
: {
|
||||
data: TData extends Record<string, unknown>
|
||||
? TData[keyof TData]
|
||||
: TData;
|
||||
request: Request;
|
||||
response: Response;
|
||||
}
|
||||
>
|
||||
: Promise<
|
||||
TResponseStyle extends 'data'
|
||||
?
|
||||
| (TData extends Record<string, unknown>
|
||||
? TData[keyof TData]
|
||||
: TData)
|
||||
| undefined
|
||||
: (
|
||||
| {
|
||||
data: TData extends Record<string, unknown>
|
||||
? TData[keyof TData]
|
||||
: TData;
|
||||
error: undefined;
|
||||
}
|
||||
| {
|
||||
data: undefined;
|
||||
error: TError extends Record<string, unknown>
|
||||
? TError[keyof TError]
|
||||
: TError;
|
||||
}
|
||||
) & {
|
||||
request: Request;
|
||||
response: Response;
|
||||
}
|
||||
>;
|
||||
|
||||
export interface ClientOptions {
|
||||
baseUrl?: string;
|
||||
responseStyle?: ResponseStyle;
|
||||
throwOnError?: boolean;
|
||||
}
|
||||
|
||||
type MethodFn = <
|
||||
TData = unknown,
|
||||
TError = unknown,
|
||||
ThrowOnError extends boolean = false,
|
||||
TResponseStyle extends ResponseStyle = 'fields',
|
||||
>(
|
||||
options: Omit<RequestOptions<TData, TResponseStyle, ThrowOnError>, 'method'>,
|
||||
) => RequestResult<TData, TError, ThrowOnError, TResponseStyle>;
|
||||
|
||||
type SseFn = <
|
||||
TData = unknown,
|
||||
TError = unknown,
|
||||
ThrowOnError extends boolean = false,
|
||||
TResponseStyle extends ResponseStyle = 'fields',
|
||||
>(
|
||||
options: Omit<RequestOptions<TData, TResponseStyle, ThrowOnError>, 'method'>,
|
||||
) => Promise<ServerSentEventsResult<TData, TError>>;
|
||||
|
||||
type RequestFn = <
|
||||
TData = unknown,
|
||||
TError = unknown,
|
||||
ThrowOnError extends boolean = false,
|
||||
TResponseStyle extends ResponseStyle = 'fields',
|
||||
>(
|
||||
options: Omit<RequestOptions<TData, TResponseStyle, ThrowOnError>, 'method'> &
|
||||
Pick<
|
||||
Required<RequestOptions<TData, TResponseStyle, ThrowOnError>>,
|
||||
'method'
|
||||
>,
|
||||
) => RequestResult<TData, TError, ThrowOnError, TResponseStyle>;
|
||||
|
||||
type BuildUrlFn = <
|
||||
TData extends {
|
||||
body?: unknown;
|
||||
path?: Record<string, unknown>;
|
||||
query?: Record<string, unknown>;
|
||||
url: string;
|
||||
},
|
||||
>(
|
||||
options: TData & Options<TData>,
|
||||
) => string;
|
||||
|
||||
export type Client = CoreClient<
|
||||
RequestFn,
|
||||
Config,
|
||||
MethodFn,
|
||||
BuildUrlFn,
|
||||
SseFn
|
||||
> & {
|
||||
interceptors: Middleware<Request, Response, unknown, ResolvedRequestOptions>;
|
||||
};
|
||||
|
||||
/**
|
||||
* The `createClientConfig()` function will be called on client initialization
|
||||
* and the returned object will become the client's initial configuration.
|
||||
*
|
||||
* You may want to initialize your client this way instead of calling
|
||||
* `setConfig()`. This is useful for example if you're using Next.js
|
||||
* to ensure your client always has the correct values.
|
||||
*/
|
||||
export type CreateClientConfig<T extends ClientOptions = ClientOptions> = (
|
||||
override?: Config<ClientOptions & T>,
|
||||
) => Config<Required<ClientOptions> & T>;
|
||||
|
||||
export interface TDataShape {
|
||||
body?: unknown;
|
||||
headers?: unknown;
|
||||
path?: unknown;
|
||||
query?: unknown;
|
||||
url: string;
|
||||
}
|
||||
|
||||
type OmitKeys<T, K> = Pick<T, Exclude<keyof T, K>>;
|
||||
|
||||
export type Options<
|
||||
TData extends TDataShape = TDataShape,
|
||||
ThrowOnError extends boolean = boolean,
|
||||
TResponse = unknown,
|
||||
TResponseStyle extends ResponseStyle = 'fields',
|
||||
> = OmitKeys<
|
||||
RequestOptions<TResponse, TResponseStyle, ThrowOnError>,
|
||||
'body' | 'path' | 'query' | 'url'
|
||||
> &
|
||||
([TData] extends [never] ? unknown : Omit<TData, 'url'>);
|
||||
332
packages/sdk/js/src/v2/gen/client/utils.gen.ts
Normal file
332
packages/sdk/js/src/v2/gen/client/utils.gen.ts
Normal file
|
|
@ -0,0 +1,332 @@
|
|||
// This file is auto-generated by @hey-api/openapi-ts
|
||||
|
||||
import { getAuthToken } from '../core/auth.gen.js';
|
||||
import type { QuerySerializerOptions } from '../core/bodySerializer.gen.js';
|
||||
import { jsonBodySerializer } from '../core/bodySerializer.gen.js';
|
||||
import {
|
||||
serializeArrayParam,
|
||||
serializeObjectParam,
|
||||
serializePrimitiveParam,
|
||||
} from '../core/pathSerializer.gen.js';
|
||||
import { getUrl } from '../core/utils.gen.js';
|
||||
import type { Client, ClientOptions, Config, RequestOptions } from './types.gen.js';
|
||||
|
||||
export const createQuerySerializer = <T = unknown>({
|
||||
parameters = {},
|
||||
...args
|
||||
}: QuerySerializerOptions = {}) => {
|
||||
const querySerializer = (queryParams: T) => {
|
||||
const search: string[] = [];
|
||||
if (queryParams && typeof queryParams === 'object') {
|
||||
for (const name in queryParams) {
|
||||
const value = queryParams[name];
|
||||
|
||||
if (value === undefined || value === null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const options = parameters[name] || args;
|
||||
|
||||
if (Array.isArray(value)) {
|
||||
const serializedArray = serializeArrayParam({
|
||||
allowReserved: options.allowReserved,
|
||||
explode: true,
|
||||
name,
|
||||
style: 'form',
|
||||
value,
|
||||
...options.array,
|
||||
});
|
||||
if (serializedArray) search.push(serializedArray);
|
||||
} else if (typeof value === 'object') {
|
||||
const serializedObject = serializeObjectParam({
|
||||
allowReserved: options.allowReserved,
|
||||
explode: true,
|
||||
name,
|
||||
style: 'deepObject',
|
||||
value: value as Record<string, unknown>,
|
||||
...options.object,
|
||||
});
|
||||
if (serializedObject) search.push(serializedObject);
|
||||
} else {
|
||||
const serializedPrimitive = serializePrimitiveParam({
|
||||
allowReserved: options.allowReserved,
|
||||
name,
|
||||
value: value as string,
|
||||
});
|
||||
if (serializedPrimitive) search.push(serializedPrimitive);
|
||||
}
|
||||
}
|
||||
}
|
||||
return search.join('&');
|
||||
};
|
||||
return querySerializer;
|
||||
};
|
||||
|
||||
/**
|
||||
* Infers parseAs value from provided Content-Type header.
|
||||
*/
|
||||
export const getParseAs = (
|
||||
contentType: string | null,
|
||||
): Exclude<Config['parseAs'], 'auto'> => {
|
||||
if (!contentType) {
|
||||
// If no Content-Type header is provided, the best we can do is return the raw response body,
|
||||
// which is effectively the same as the 'stream' option.
|
||||
return 'stream';
|
||||
}
|
||||
|
||||
const cleanContent = contentType.split(';')[0]?.trim();
|
||||
|
||||
if (!cleanContent) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (
|
||||
cleanContent.startsWith('application/json') ||
|
||||
cleanContent.endsWith('+json')
|
||||
) {
|
||||
return 'json';
|
||||
}
|
||||
|
||||
if (cleanContent === 'multipart/form-data') {
|
||||
return 'formData';
|
||||
}
|
||||
|
||||
if (
|
||||
['application/', 'audio/', 'image/', 'video/'].some((type) =>
|
||||
cleanContent.startsWith(type),
|
||||
)
|
||||
) {
|
||||
return 'blob';
|
||||
}
|
||||
|
||||
if (cleanContent.startsWith('text/')) {
|
||||
return 'text';
|
||||
}
|
||||
|
||||
return;
|
||||
};
|
||||
|
||||
const checkForExistence = (
|
||||
options: Pick<RequestOptions, 'auth' | 'query'> & {
|
||||
headers: Headers;
|
||||
},
|
||||
name?: string,
|
||||
): boolean => {
|
||||
if (!name) {
|
||||
return false;
|
||||
}
|
||||
if (
|
||||
options.headers.has(name) ||
|
||||
options.query?.[name] ||
|
||||
options.headers.get('Cookie')?.includes(`${name}=`)
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
};
|
||||
|
||||
export const setAuthParams = async ({
|
||||
security,
|
||||
...options
|
||||
}: Pick<Required<RequestOptions>, 'security'> &
|
||||
Pick<RequestOptions, 'auth' | 'query'> & {
|
||||
headers: Headers;
|
||||
}) => {
|
||||
for (const auth of security) {
|
||||
if (checkForExistence(options, auth.name)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const token = await getAuthToken(auth, options.auth);
|
||||
|
||||
if (!token) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const name = auth.name ?? 'Authorization';
|
||||
|
||||
switch (auth.in) {
|
||||
case 'query':
|
||||
if (!options.query) {
|
||||
options.query = {};
|
||||
}
|
||||
options.query[name] = token;
|
||||
break;
|
||||
case 'cookie':
|
||||
options.headers.append('Cookie', `${name}=${token}`);
|
||||
break;
|
||||
case 'header':
|
||||
default:
|
||||
options.headers.set(name, token);
|
||||
break;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
export const buildUrl: Client['buildUrl'] = (options) =>
|
||||
getUrl({
|
||||
baseUrl: options.baseUrl as string,
|
||||
path: options.path,
|
||||
query: options.query,
|
||||
querySerializer:
|
||||
typeof options.querySerializer === 'function'
|
||||
? options.querySerializer
|
||||
: createQuerySerializer(options.querySerializer),
|
||||
url: options.url,
|
||||
});
|
||||
|
||||
export const mergeConfigs = (a: Config, b: Config): Config => {
|
||||
const config = { ...a, ...b };
|
||||
if (config.baseUrl?.endsWith('/')) {
|
||||
config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1);
|
||||
}
|
||||
config.headers = mergeHeaders(a.headers, b.headers);
|
||||
return config;
|
||||
};
|
||||
|
||||
const headersEntries = (headers: Headers): Array<[string, string]> => {
|
||||
const entries: Array<[string, string]> = [];
|
||||
headers.forEach((value, key) => {
|
||||
entries.push([key, value]);
|
||||
});
|
||||
return entries;
|
||||
};
|
||||
|
||||
export const mergeHeaders = (
|
||||
...headers: Array<Required<Config>['headers'] | undefined>
|
||||
): Headers => {
|
||||
const mergedHeaders = new Headers();
|
||||
for (const header of headers) {
|
||||
if (!header) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const iterator =
|
||||
header instanceof Headers
|
||||
? headersEntries(header)
|
||||
: Object.entries(header);
|
||||
|
||||
for (const [key, value] of iterator) {
|
||||
if (value === null) {
|
||||
mergedHeaders.delete(key);
|
||||
} else if (Array.isArray(value)) {
|
||||
for (const v of value) {
|
||||
mergedHeaders.append(key, v as string);
|
||||
}
|
||||
} else if (value !== undefined) {
|
||||
// assume object headers are meant to be JSON stringified, i.e. their
|
||||
// content value in OpenAPI specification is 'application/json'
|
||||
mergedHeaders.set(
|
||||
key,
|
||||
typeof value === 'object' ? JSON.stringify(value) : (value as string),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
return mergedHeaders;
|
||||
};
|
||||
|
||||
type ErrInterceptor<Err, Res, Req, Options> = (
|
||||
error: Err,
|
||||
response: Res,
|
||||
request: Req,
|
||||
options: Options,
|
||||
) => Err | Promise<Err>;
|
||||
|
||||
type ReqInterceptor<Req, Options> = (
|
||||
request: Req,
|
||||
options: Options,
|
||||
) => Req | Promise<Req>;
|
||||
|
||||
type ResInterceptor<Res, Req, Options> = (
|
||||
response: Res,
|
||||
request: Req,
|
||||
options: Options,
|
||||
) => Res | Promise<Res>;
|
||||
|
||||
class Interceptors<Interceptor> {
|
||||
fns: Array<Interceptor | null> = [];
|
||||
|
||||
clear(): void {
|
||||
this.fns = [];
|
||||
}
|
||||
|
||||
eject(id: number | Interceptor): void {
|
||||
const index = this.getInterceptorIndex(id);
|
||||
if (this.fns[index]) {
|
||||
this.fns[index] = null;
|
||||
}
|
||||
}
|
||||
|
||||
exists(id: number | Interceptor): boolean {
|
||||
const index = this.getInterceptorIndex(id);
|
||||
return Boolean(this.fns[index]);
|
||||
}
|
||||
|
||||
getInterceptorIndex(id: number | Interceptor): number {
|
||||
if (typeof id === 'number') {
|
||||
return this.fns[id] ? id : -1;
|
||||
}
|
||||
return this.fns.indexOf(id);
|
||||
}
|
||||
|
||||
update(
|
||||
id: number | Interceptor,
|
||||
fn: Interceptor,
|
||||
): number | Interceptor | false {
|
||||
const index = this.getInterceptorIndex(id);
|
||||
if (this.fns[index]) {
|
||||
this.fns[index] = fn;
|
||||
return id;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
use(fn: Interceptor): number {
|
||||
this.fns.push(fn);
|
||||
return this.fns.length - 1;
|
||||
}
|
||||
}
|
||||
|
||||
export interface Middleware<Req, Res, Err, Options> {
|
||||
error: Interceptors<ErrInterceptor<Err, Res, Req, Options>>;
|
||||
request: Interceptors<ReqInterceptor<Req, Options>>;
|
||||
response: Interceptors<ResInterceptor<Res, Req, Options>>;
|
||||
}
|
||||
|
||||
export const createInterceptors = <Req, Res, Err, Options>(): Middleware<
|
||||
Req,
|
||||
Res,
|
||||
Err,
|
||||
Options
|
||||
> => ({
|
||||
error: new Interceptors<ErrInterceptor<Err, Res, Req, Options>>(),
|
||||
request: new Interceptors<ReqInterceptor<Req, Options>>(),
|
||||
response: new Interceptors<ResInterceptor<Res, Req, Options>>(),
|
||||
});
|
||||
|
||||
const defaultQuerySerializer = createQuerySerializer({
|
||||
allowReserved: false,
|
||||
array: {
|
||||
explode: true,
|
||||
style: 'form',
|
||||
},
|
||||
object: {
|
||||
explode: true,
|
||||
style: 'deepObject',
|
||||
},
|
||||
});
|
||||
|
||||
const defaultHeaders = {
|
||||
'Content-Type': 'application/json',
|
||||
};
|
||||
|
||||
export const createConfig = <T extends ClientOptions = ClientOptions>(
|
||||
override: Config<Omit<ClientOptions, keyof T> & T> = {},
|
||||
): Config<Omit<ClientOptions, keyof T> & T> => ({
|
||||
...jsonBodySerializer,
|
||||
headers: defaultHeaders,
|
||||
parseAs: 'auto',
|
||||
querySerializer: defaultQuerySerializer,
|
||||
...override,
|
||||
});
|
||||
42
packages/sdk/js/src/v2/gen/core/auth.gen.ts
Normal file
42
packages/sdk/js/src/v2/gen/core/auth.gen.ts
Normal file
|
|
@ -0,0 +1,42 @@
|
|||
// This file is auto-generated by @hey-api/openapi-ts
|
||||
|
||||
export type AuthToken = string | undefined;
|
||||
|
||||
export interface Auth {
|
||||
/**
|
||||
* Which part of the request do we use to send the auth?
|
||||
*
|
||||
* @default 'header'
|
||||
*/
|
||||
in?: 'header' | 'query' | 'cookie';
|
||||
/**
|
||||
* Header or query parameter name.
|
||||
*
|
||||
* @default 'Authorization'
|
||||
*/
|
||||
name?: string;
|
||||
scheme?: 'basic' | 'bearer';
|
||||
type: 'apiKey' | 'http';
|
||||
}
|
||||
|
||||
export const getAuthToken = async (
|
||||
auth: Auth,
|
||||
callback: ((auth: Auth) => Promise<AuthToken> | AuthToken) | AuthToken,
|
||||
): Promise<string | undefined> => {
|
||||
const token =
|
||||
typeof callback === 'function' ? await callback(auth) : callback;
|
||||
|
||||
if (!token) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (auth.scheme === 'bearer') {
|
||||
return `Bearer ${token}`;
|
||||
}
|
||||
|
||||
if (auth.scheme === 'basic') {
|
||||
return `Basic ${btoa(token)}`;
|
||||
}
|
||||
|
||||
return token;
|
||||
};
|
||||
100
packages/sdk/js/src/v2/gen/core/bodySerializer.gen.ts
Normal file
100
packages/sdk/js/src/v2/gen/core/bodySerializer.gen.ts
Normal file
|
|
@ -0,0 +1,100 @@
|
|||
// This file is auto-generated by @hey-api/openapi-ts
|
||||
|
||||
import type {
|
||||
ArrayStyle,
|
||||
ObjectStyle,
|
||||
SerializerOptions,
|
||||
} from './pathSerializer.gen.js';
|
||||
|
||||
export type QuerySerializer = (query: Record<string, unknown>) => string;
|
||||
|
||||
export type BodySerializer = (body: any) => any;
|
||||
|
||||
type QuerySerializerOptionsObject = {
|
||||
allowReserved?: boolean;
|
||||
array?: Partial<SerializerOptions<ArrayStyle>>;
|
||||
object?: Partial<SerializerOptions<ObjectStyle>>;
|
||||
};
|
||||
|
||||
export type QuerySerializerOptions = QuerySerializerOptionsObject & {
|
||||
/**
|
||||
* Per-parameter serialization overrides. When provided, these settings
|
||||
* override the global array/object settings for specific parameter names.
|
||||
*/
|
||||
parameters?: Record<string, QuerySerializerOptionsObject>;
|
||||
};
|
||||
|
||||
const serializeFormDataPair = (
|
||||
data: FormData,
|
||||
key: string,
|
||||
value: unknown,
|
||||
): void => {
|
||||
if (typeof value === 'string' || value instanceof Blob) {
|
||||
data.append(key, value);
|
||||
} else if (value instanceof Date) {
|
||||
data.append(key, value.toISOString());
|
||||
} else {
|
||||
data.append(key, JSON.stringify(value));
|
||||
}
|
||||
};
|
||||
|
||||
const serializeUrlSearchParamsPair = (
|
||||
data: URLSearchParams,
|
||||
key: string,
|
||||
value: unknown,
|
||||
): void => {
|
||||
if (typeof value === 'string') {
|
||||
data.append(key, value);
|
||||
} else {
|
||||
data.append(key, JSON.stringify(value));
|
||||
}
|
||||
};
|
||||
|
||||
export const formDataBodySerializer = {
|
||||
bodySerializer: <T extends Record<string, any> | Array<Record<string, any>>>(
|
||||
body: T,
|
||||
): FormData => {
|
||||
const data = new FormData();
|
||||
|
||||
Object.entries(body).forEach(([key, value]) => {
|
||||
if (value === undefined || value === null) {
|
||||
return;
|
||||
}
|
||||
if (Array.isArray(value)) {
|
||||
value.forEach((v) => serializeFormDataPair(data, key, v));
|
||||
} else {
|
||||
serializeFormDataPair(data, key, value);
|
||||
}
|
||||
});
|
||||
|
||||
return data;
|
||||
},
|
||||
};
|
||||
|
||||
export const jsonBodySerializer = {
|
||||
bodySerializer: <T>(body: T): string =>
|
||||
JSON.stringify(body, (_key, value) =>
|
||||
typeof value === 'bigint' ? value.toString() : value,
|
||||
),
|
||||
};
|
||||
|
||||
export const urlSearchParamsBodySerializer = {
|
||||
bodySerializer: <T extends Record<string, any> | Array<Record<string, any>>>(
|
||||
body: T,
|
||||
): string => {
|
||||
const data = new URLSearchParams();
|
||||
|
||||
Object.entries(body).forEach(([key, value]) => {
|
||||
if (value === undefined || value === null) {
|
||||
return;
|
||||
}
|
||||
if (Array.isArray(value)) {
|
||||
value.forEach((v) => serializeUrlSearchParamsPair(data, key, v));
|
||||
} else {
|
||||
serializeUrlSearchParamsPair(data, key, value);
|
||||
}
|
||||
});
|
||||
|
||||
return data.toString();
|
||||
},
|
||||
};
|
||||
176
packages/sdk/js/src/v2/gen/core/params.gen.ts
Normal file
176
packages/sdk/js/src/v2/gen/core/params.gen.ts
Normal file
|
|
@ -0,0 +1,176 @@
|
|||
// This file is auto-generated by @hey-api/openapi-ts
|
||||
|
||||
type Slot = 'body' | 'headers' | 'path' | 'query';
|
||||
|
||||
export type Field =
|
||||
| {
|
||||
in: Exclude<Slot, 'body'>;
|
||||
/**
|
||||
* Field name. This is the name we want the user to see and use.
|
||||
*/
|
||||
key: string;
|
||||
/**
|
||||
* Field mapped name. This is the name we want to use in the request.
|
||||
* If omitted, we use the same value as `key`.
|
||||
*/
|
||||
map?: string;
|
||||
}
|
||||
| {
|
||||
in: Extract<Slot, 'body'>;
|
||||
/**
|
||||
* Key isn't required for bodies.
|
||||
*/
|
||||
key?: string;
|
||||
map?: string;
|
||||
}
|
||||
| {
|
||||
/**
|
||||
* Field name. This is the name we want the user to see and use.
|
||||
*/
|
||||
key: string;
|
||||
/**
|
||||
* Field mapped name. This is the name we want to use in the request.
|
||||
* If `in` is omitted, `map` aliases `key` to the transport layer.
|
||||
*/
|
||||
map: Slot;
|
||||
};
|
||||
|
||||
export interface Fields {
|
||||
allowExtra?: Partial<Record<Slot, boolean>>;
|
||||
args?: ReadonlyArray<Field>;
|
||||
}
|
||||
|
||||
export type FieldsConfig = ReadonlyArray<Field | Fields>;
|
||||
|
||||
const extraPrefixesMap: Record<string, Slot> = {
|
||||
$body_: 'body',
|
||||
$headers_: 'headers',
|
||||
$path_: 'path',
|
||||
$query_: 'query',
|
||||
};
|
||||
const extraPrefixes = Object.entries(extraPrefixesMap);
|
||||
|
||||
type KeyMap = Map<
|
||||
string,
|
||||
| {
|
||||
in: Slot;
|
||||
map?: string;
|
||||
}
|
||||
| {
|
||||
in?: never;
|
||||
map: Slot;
|
||||
}
|
||||
>;
|
||||
|
||||
const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => {
|
||||
if (!map) {
|
||||
map = new Map();
|
||||
}
|
||||
|
||||
for (const config of fields) {
|
||||
if ('in' in config) {
|
||||
if (config.key) {
|
||||
map.set(config.key, {
|
||||
in: config.in,
|
||||
map: config.map,
|
||||
});
|
||||
}
|
||||
} else if ('key' in config) {
|
||||
map.set(config.key, {
|
||||
map: config.map,
|
||||
});
|
||||
} else if (config.args) {
|
||||
buildKeyMap(config.args, map);
|
||||
}
|
||||
}
|
||||
|
||||
return map;
|
||||
};
|
||||
|
||||
interface Params {
|
||||
body: unknown;
|
||||
headers: Record<string, unknown>;
|
||||
path: Record<string, unknown>;
|
||||
query: Record<string, unknown>;
|
||||
}
|
||||
|
||||
const stripEmptySlots = (params: Params) => {
|
||||
for (const [slot, value] of Object.entries(params)) {
|
||||
if (value && typeof value === 'object' && !Object.keys(value).length) {
|
||||
delete params[slot as Slot];
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
export const buildClientParams = (
|
||||
args: ReadonlyArray<unknown>,
|
||||
fields: FieldsConfig,
|
||||
) => {
|
||||
const params: Params = {
|
||||
body: {},
|
||||
headers: {},
|
||||
path: {},
|
||||
query: {},
|
||||
};
|
||||
|
||||
const map = buildKeyMap(fields);
|
||||
|
||||
let config: FieldsConfig[number] | undefined;
|
||||
|
||||
for (const [index, arg] of args.entries()) {
|
||||
if (fields[index]) {
|
||||
config = fields[index];
|
||||
}
|
||||
|
||||
if (!config) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if ('in' in config) {
|
||||
if (config.key) {
|
||||
const field = map.get(config.key)!;
|
||||
const name = field.map || config.key;
|
||||
if (field.in) {
|
||||
(params[field.in] as Record<string, unknown>)[name] = arg;
|
||||
}
|
||||
} else {
|
||||
params.body = arg;
|
||||
}
|
||||
} else {
|
||||
for (const [key, value] of Object.entries(arg ?? {})) {
|
||||
const field = map.get(key);
|
||||
|
||||
if (field) {
|
||||
if (field.in) {
|
||||
const name = field.map || key;
|
||||
(params[field.in] as Record<string, unknown>)[name] = value;
|
||||
} else {
|
||||
params[field.map] = value;
|
||||
}
|
||||
} else {
|
||||
const extra = extraPrefixes.find(([prefix]) =>
|
||||
key.startsWith(prefix),
|
||||
);
|
||||
|
||||
if (extra) {
|
||||
const [prefix, slot] = extra;
|
||||
(params[slot] as Record<string, unknown>)[
|
||||
key.slice(prefix.length)
|
||||
] = value;
|
||||
} else if ('allowExtra' in config && config.allowExtra) {
|
||||
for (const [slot, allowed] of Object.entries(config.allowExtra)) {
|
||||
if (allowed) {
|
||||
(params[slot as Slot] as Record<string, unknown>)[key] = value;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
stripEmptySlots(params);
|
||||
|
||||
return params;
|
||||
};
|
||||
181
packages/sdk/js/src/v2/gen/core/pathSerializer.gen.ts
Normal file
181
packages/sdk/js/src/v2/gen/core/pathSerializer.gen.ts
Normal file
|
|
@ -0,0 +1,181 @@
|
|||
// This file is auto-generated by @hey-api/openapi-ts
|
||||
|
||||
interface SerializeOptions<T>
|
||||
extends SerializePrimitiveOptions,
|
||||
SerializerOptions<T> {}
|
||||
|
||||
interface SerializePrimitiveOptions {
|
||||
allowReserved?: boolean;
|
||||
name: string;
|
||||
}
|
||||
|
||||
export interface SerializerOptions<T> {
|
||||
/**
|
||||
* @default true
|
||||
*/
|
||||
explode: boolean;
|
||||
style: T;
|
||||
}
|
||||
|
||||
export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited';
|
||||
export type ArraySeparatorStyle = ArrayStyle | MatrixStyle;
|
||||
type MatrixStyle = 'label' | 'matrix' | 'simple';
|
||||
export type ObjectStyle = 'form' | 'deepObject';
|
||||
type ObjectSeparatorStyle = ObjectStyle | MatrixStyle;
|
||||
|
||||
interface SerializePrimitiveParam extends SerializePrimitiveOptions {
|
||||
value: string;
|
||||
}
|
||||
|
||||
export const separatorArrayExplode = (style: ArraySeparatorStyle) => {
|
||||
switch (style) {
|
||||
case 'label':
|
||||
return '.';
|
||||
case 'matrix':
|
||||
return ';';
|
||||
case 'simple':
|
||||
return ',';
|
||||
default:
|
||||
return '&';
|
||||
}
|
||||
};
|
||||
|
||||
export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => {
|
||||
switch (style) {
|
||||
case 'form':
|
||||
return ',';
|
||||
case 'pipeDelimited':
|
||||
return '|';
|
||||
case 'spaceDelimited':
|
||||
return '%20';
|
||||
default:
|
||||
return ',';
|
||||
}
|
||||
};
|
||||
|
||||
export const separatorObjectExplode = (style: ObjectSeparatorStyle) => {
|
||||
switch (style) {
|
||||
case 'label':
|
||||
return '.';
|
||||
case 'matrix':
|
||||
return ';';
|
||||
case 'simple':
|
||||
return ',';
|
||||
default:
|
||||
return '&';
|
||||
}
|
||||
};
|
||||
|
||||
export const serializeArrayParam = ({
|
||||
allowReserved,
|
||||
explode,
|
||||
name,
|
||||
style,
|
||||
value,
|
||||
}: SerializeOptions<ArraySeparatorStyle> & {
|
||||
value: unknown[];
|
||||
}) => {
|
||||
if (!explode) {
|
||||
const joinedValues = (
|
||||
allowReserved ? value : value.map((v) => encodeURIComponent(v as string))
|
||||
).join(separatorArrayNoExplode(style));
|
||||
switch (style) {
|
||||
case 'label':
|
||||
return `.${joinedValues}`;
|
||||
case 'matrix':
|
||||
return `;${name}=${joinedValues}`;
|
||||
case 'simple':
|
||||
return joinedValues;
|
||||
default:
|
||||
return `${name}=${joinedValues}`;
|
||||
}
|
||||
}
|
||||
|
||||
const separator = separatorArrayExplode(style);
|
||||
const joinedValues = value
|
||||
.map((v) => {
|
||||
if (style === 'label' || style === 'simple') {
|
||||
return allowReserved ? v : encodeURIComponent(v as string);
|
||||
}
|
||||
|
||||
return serializePrimitiveParam({
|
||||
allowReserved,
|
||||
name,
|
||||
value: v as string,
|
||||
});
|
||||
})
|
||||
.join(separator);
|
||||
return style === 'label' || style === 'matrix'
|
||||
? separator + joinedValues
|
||||
: joinedValues;
|
||||
};
|
||||
|
||||
export const serializePrimitiveParam = ({
|
||||
allowReserved,
|
||||
name,
|
||||
value,
|
||||
}: SerializePrimitiveParam) => {
|
||||
if (value === undefined || value === null) {
|
||||
return '';
|
||||
}
|
||||
|
||||
if (typeof value === 'object') {
|
||||
throw new Error(
|
||||
'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.',
|
||||
);
|
||||
}
|
||||
|
||||
return `${name}=${allowReserved ? value : encodeURIComponent(value)}`;
|
||||
};
|
||||
|
||||
export const serializeObjectParam = ({
|
||||
allowReserved,
|
||||
explode,
|
||||
name,
|
||||
style,
|
||||
value,
|
||||
valueOnly,
|
||||
}: SerializeOptions<ObjectSeparatorStyle> & {
|
||||
value: Record<string, unknown> | Date;
|
||||
valueOnly?: boolean;
|
||||
}) => {
|
||||
if (value instanceof Date) {
|
||||
return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`;
|
||||
}
|
||||
|
||||
if (style !== 'deepObject' && !explode) {
|
||||
let values: string[] = [];
|
||||
Object.entries(value).forEach(([key, v]) => {
|
||||
values = [
|
||||
...values,
|
||||
key,
|
||||
allowReserved ? (v as string) : encodeURIComponent(v as string),
|
||||
];
|
||||
});
|
||||
const joinedValues = values.join(',');
|
||||
switch (style) {
|
||||
case 'form':
|
||||
return `${name}=${joinedValues}`;
|
||||
case 'label':
|
||||
return `.${joinedValues}`;
|
||||
case 'matrix':
|
||||
return `;${name}=${joinedValues}`;
|
||||
default:
|
||||
return joinedValues;
|
||||
}
|
||||
}
|
||||
|
||||
const separator = separatorObjectExplode(style);
|
||||
const joinedValues = Object.entries(value)
|
||||
.map(([key, v]) =>
|
||||
serializePrimitiveParam({
|
||||
allowReserved,
|
||||
name: style === 'deepObject' ? `${name}[${key}]` : key,
|
||||
value: v as string,
|
||||
}),
|
||||
)
|
||||
.join(separator);
|
||||
return style === 'label' || style === 'matrix'
|
||||
? separator + joinedValues
|
||||
: joinedValues;
|
||||
};
|
||||
136
packages/sdk/js/src/v2/gen/core/queryKeySerializer.gen.ts
Normal file
136
packages/sdk/js/src/v2/gen/core/queryKeySerializer.gen.ts
Normal file
|
|
@ -0,0 +1,136 @@
|
|||
// This file is auto-generated by @hey-api/openapi-ts
|
||||
|
||||
/**
|
||||
* JSON-friendly union that mirrors what Pinia Colada can hash.
|
||||
*/
|
||||
export type JsonValue =
|
||||
| null
|
||||
| string
|
||||
| number
|
||||
| boolean
|
||||
| JsonValue[]
|
||||
| { [key: string]: JsonValue };
|
||||
|
||||
/**
|
||||
* Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes.
|
||||
*/
|
||||
export const queryKeyJsonReplacer = (_key: string, value: unknown) => {
|
||||
if (
|
||||
value === undefined ||
|
||||
typeof value === 'function' ||
|
||||
typeof value === 'symbol'
|
||||
) {
|
||||
return undefined;
|
||||
}
|
||||
if (typeof value === 'bigint') {
|
||||
return value.toString();
|
||||
}
|
||||
if (value instanceof Date) {
|
||||
return value.toISOString();
|
||||
}
|
||||
return value;
|
||||
};
|
||||
|
||||
/**
|
||||
* Safely stringifies a value and parses it back into a JsonValue.
|
||||
*/
|
||||
export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => {
|
||||
try {
|
||||
const json = JSON.stringify(input, queryKeyJsonReplacer);
|
||||
if (json === undefined) {
|
||||
return undefined;
|
||||
}
|
||||
return JSON.parse(json) as JsonValue;
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Detects plain objects (including objects with a null prototype).
|
||||
*/
|
||||
const isPlainObject = (value: unknown): value is Record<string, unknown> => {
|
||||
if (value === null || typeof value !== 'object') {
|
||||
return false;
|
||||
}
|
||||
const prototype = Object.getPrototypeOf(value as object);
|
||||
return prototype === Object.prototype || prototype === null;
|
||||
};
|
||||
|
||||
/**
|
||||
* Turns URLSearchParams into a sorted JSON object for deterministic keys.
|
||||
*/
|
||||
const serializeSearchParams = (params: URLSearchParams): JsonValue => {
|
||||
const entries = Array.from(params.entries()).sort(([a], [b]) =>
|
||||
a.localeCompare(b),
|
||||
);
|
||||
const result: Record<string, JsonValue> = {};
|
||||
|
||||
for (const [key, value] of entries) {
|
||||
const existing = result[key];
|
||||
if (existing === undefined) {
|
||||
result[key] = value;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (Array.isArray(existing)) {
|
||||
(existing as string[]).push(value);
|
||||
} else {
|
||||
result[key] = [existing, value];
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
};
|
||||
|
||||
/**
|
||||
* Normalizes any accepted value into a JSON-friendly shape for query keys.
|
||||
*/
|
||||
export const serializeQueryKeyValue = (
|
||||
value: unknown,
|
||||
): JsonValue | undefined => {
|
||||
if (value === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (
|
||||
typeof value === 'string' ||
|
||||
typeof value === 'number' ||
|
||||
typeof value === 'boolean'
|
||||
) {
|
||||
return value;
|
||||
}
|
||||
|
||||
if (
|
||||
value === undefined ||
|
||||
typeof value === 'function' ||
|
||||
typeof value === 'symbol'
|
||||
) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
if (typeof value === 'bigint') {
|
||||
return value.toString();
|
||||
}
|
||||
|
||||
if (value instanceof Date) {
|
||||
return value.toISOString();
|
||||
}
|
||||
|
||||
if (Array.isArray(value)) {
|
||||
return stringifyToJsonValue(value);
|
||||
}
|
||||
|
||||
if (
|
||||
typeof URLSearchParams !== 'undefined' &&
|
||||
value instanceof URLSearchParams
|
||||
) {
|
||||
return serializeSearchParams(value);
|
||||
}
|
||||
|
||||
if (isPlainObject(value)) {
|
||||
return stringifyToJsonValue(value);
|
||||
}
|
||||
|
||||
return undefined;
|
||||
};
|
||||
264
packages/sdk/js/src/v2/gen/core/serverSentEvents.gen.ts
Normal file
264
packages/sdk/js/src/v2/gen/core/serverSentEvents.gen.ts
Normal file
|
|
@ -0,0 +1,264 @@
|
|||
// This file is auto-generated by @hey-api/openapi-ts
|
||||
|
||||
import type { Config } from './types.gen.js';
|
||||
|
||||
export type ServerSentEventsOptions<TData = unknown> = Omit<
|
||||
RequestInit,
|
||||
'method'
|
||||
> &
|
||||
Pick<Config, 'method' | 'responseTransformer' | 'responseValidator'> & {
|
||||
/**
|
||||
* Fetch API implementation. You can use this option to provide a custom
|
||||
* fetch instance.
|
||||
*
|
||||
* @default globalThis.fetch
|
||||
*/
|
||||
fetch?: typeof fetch;
|
||||
/**
|
||||
* Implementing clients can call request interceptors inside this hook.
|
||||
*/
|
||||
onRequest?: (url: string, init: RequestInit) => Promise<Request>;
|
||||
/**
|
||||
* Callback invoked when a network or parsing error occurs during streaming.
|
||||
*
|
||||
* This option applies only if the endpoint returns a stream of events.
|
||||
*
|
||||
* @param error The error that occurred.
|
||||
*/
|
||||
onSseError?: (error: unknown) => void;
|
||||
/**
|
||||
* Callback invoked when an event is streamed from the server.
|
||||
*
|
||||
* This option applies only if the endpoint returns a stream of events.
|
||||
*
|
||||
* @param event Event streamed from the server.
|
||||
* @returns Nothing (void).
|
||||
*/
|
||||
onSseEvent?: (event: StreamEvent<TData>) => void;
|
||||
serializedBody?: RequestInit['body'];
|
||||
/**
|
||||
* Default retry delay in milliseconds.
|
||||
*
|
||||
* This option applies only if the endpoint returns a stream of events.
|
||||
*
|
||||
* @default 3000
|
||||
*/
|
||||
sseDefaultRetryDelay?: number;
|
||||
/**
|
||||
* Maximum number of retry attempts before giving up.
|
||||
*/
|
||||
sseMaxRetryAttempts?: number;
|
||||
/**
|
||||
* Maximum retry delay in milliseconds.
|
||||
*
|
||||
* Applies only when exponential backoff is used.
|
||||
*
|
||||
* This option applies only if the endpoint returns a stream of events.
|
||||
*
|
||||
* @default 30000
|
||||
*/
|
||||
sseMaxRetryDelay?: number;
|
||||
/**
|
||||
* Optional sleep function for retry backoff.
|
||||
*
|
||||
* Defaults to using `setTimeout`.
|
||||
*/
|
||||
sseSleepFn?: (ms: number) => Promise<void>;
|
||||
url: string;
|
||||
};
|
||||
|
||||
export interface StreamEvent<TData = unknown> {
|
||||
data: TData;
|
||||
event?: string;
|
||||
id?: string;
|
||||
retry?: number;
|
||||
}
|
||||
|
||||
export type ServerSentEventsResult<
|
||||
TData = unknown,
|
||||
TReturn = void,
|
||||
TNext = unknown,
|
||||
> = {
|
||||
stream: AsyncGenerator<
|
||||
TData extends Record<string, unknown> ? TData[keyof TData] : TData,
|
||||
TReturn,
|
||||
TNext
|
||||
>;
|
||||
};
|
||||
|
||||
export const createSseClient = <TData = unknown>({
|
||||
onRequest,
|
||||
onSseError,
|
||||
onSseEvent,
|
||||
responseTransformer,
|
||||
responseValidator,
|
||||
sseDefaultRetryDelay,
|
||||
sseMaxRetryAttempts,
|
||||
sseMaxRetryDelay,
|
||||
sseSleepFn,
|
||||
url,
|
||||
...options
|
||||
}: ServerSentEventsOptions): ServerSentEventsResult<TData> => {
|
||||
let lastEventId: string | undefined;
|
||||
|
||||
const sleep =
|
||||
sseSleepFn ??
|
||||
((ms: number) => new Promise((resolve) => setTimeout(resolve, ms)));
|
||||
|
||||
const createStream = async function* () {
|
||||
let retryDelay: number = sseDefaultRetryDelay ?? 3000;
|
||||
let attempt = 0;
|
||||
const signal = options.signal ?? new AbortController().signal;
|
||||
|
||||
while (true) {
|
||||
if (signal.aborted) break;
|
||||
|
||||
attempt++;
|
||||
|
||||
const headers =
|
||||
options.headers instanceof Headers
|
||||
? options.headers
|
||||
: new Headers(options.headers as Record<string, string> | undefined);
|
||||
|
||||
if (lastEventId !== undefined) {
|
||||
headers.set('Last-Event-ID', lastEventId);
|
||||
}
|
||||
|
||||
try {
|
||||
const requestInit: RequestInit = {
|
||||
redirect: 'follow',
|
||||
...options,
|
||||
body: options.serializedBody,
|
||||
headers,
|
||||
signal,
|
||||
};
|
||||
let request = new Request(url, requestInit);
|
||||
if (onRequest) {
|
||||
request = await onRequest(url, requestInit);
|
||||
}
|
||||
// fetch must be assigned here, otherwise it would throw the error:
|
||||
// TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation
|
||||
const _fetch = options.fetch ?? globalThis.fetch;
|
||||
const response = await _fetch(request);
|
||||
|
||||
if (!response.ok)
|
||||
throw new Error(
|
||||
`SSE failed: ${response.status} ${response.statusText}`,
|
||||
);
|
||||
|
||||
if (!response.body) throw new Error('No body in SSE response');
|
||||
|
||||
const reader = response.body
|
||||
.pipeThrough(new TextDecoderStream())
|
||||
.getReader();
|
||||
|
||||
let buffer = '';
|
||||
|
||||
const abortHandler = () => {
|
||||
try {
|
||||
reader.cancel();
|
||||
} catch {
|
||||
// noop
|
||||
}
|
||||
};
|
||||
|
||||
signal.addEventListener('abort', abortHandler);
|
||||
|
||||
try {
|
||||
while (true) {
|
||||
const { done, value } = await reader.read();
|
||||
if (done) break;
|
||||
buffer += value;
|
||||
|
||||
const chunks = buffer.split('\n\n');
|
||||
buffer = chunks.pop() ?? '';
|
||||
|
||||
for (const chunk of chunks) {
|
||||
const lines = chunk.split('\n');
|
||||
const dataLines: Array<string> = [];
|
||||
let eventName: string | undefined;
|
||||
|
||||
for (const line of lines) {
|
||||
if (line.startsWith('data:')) {
|
||||
dataLines.push(line.replace(/^data:\s*/, ''));
|
||||
} else if (line.startsWith('event:')) {
|
||||
eventName = line.replace(/^event:\s*/, '');
|
||||
} else if (line.startsWith('id:')) {
|
||||
lastEventId = line.replace(/^id:\s*/, '');
|
||||
} else if (line.startsWith('retry:')) {
|
||||
const parsed = Number.parseInt(
|
||||
line.replace(/^retry:\s*/, ''),
|
||||
10,
|
||||
);
|
||||
if (!Number.isNaN(parsed)) {
|
||||
retryDelay = parsed;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let data: unknown;
|
||||
let parsedJson = false;
|
||||
|
||||
if (dataLines.length) {
|
||||
const rawData = dataLines.join('\n');
|
||||
try {
|
||||
data = JSON.parse(rawData);
|
||||
parsedJson = true;
|
||||
} catch {
|
||||
data = rawData;
|
||||
}
|
||||
}
|
||||
|
||||
if (parsedJson) {
|
||||
if (responseValidator) {
|
||||
await responseValidator(data);
|
||||
}
|
||||
|
||||
if (responseTransformer) {
|
||||
data = await responseTransformer(data);
|
||||
}
|
||||
}
|
||||
|
||||
onSseEvent?.({
|
||||
data,
|
||||
event: eventName,
|
||||
id: lastEventId,
|
||||
retry: retryDelay,
|
||||
});
|
||||
|
||||
if (dataLines.length) {
|
||||
yield data as any;
|
||||
}
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
signal.removeEventListener('abort', abortHandler);
|
||||
reader.releaseLock();
|
||||
}
|
||||
|
||||
break; // exit loop on normal completion
|
||||
} catch (error) {
|
||||
// connection failed or aborted; retry after delay
|
||||
onSseError?.(error);
|
||||
|
||||
if (
|
||||
sseMaxRetryAttempts !== undefined &&
|
||||
attempt >= sseMaxRetryAttempts
|
||||
) {
|
||||
break; // stop after firing error
|
||||
}
|
||||
|
||||
// exponential backoff: double retry each attempt, cap at 30s
|
||||
const backoff = Math.min(
|
||||
retryDelay * 2 ** (attempt - 1),
|
||||
sseMaxRetryDelay ?? 30000,
|
||||
);
|
||||
await sleep(backoff);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const stream = createStream();
|
||||
|
||||
return { stream };
|
||||
};
|
||||
118
packages/sdk/js/src/v2/gen/core/types.gen.ts
Normal file
118
packages/sdk/js/src/v2/gen/core/types.gen.ts
Normal file
|
|
@ -0,0 +1,118 @@
|
|||
// This file is auto-generated by @hey-api/openapi-ts
|
||||
|
||||
import type { Auth, AuthToken } from './auth.gen.js';
|
||||
import type {
|
||||
BodySerializer,
|
||||
QuerySerializer,
|
||||
QuerySerializerOptions,
|
||||
} from './bodySerializer.gen.js';
|
||||
|
||||
export type HttpMethod =
|
||||
| 'connect'
|
||||
| 'delete'
|
||||
| 'get'
|
||||
| 'head'
|
||||
| 'options'
|
||||
| 'patch'
|
||||
| 'post'
|
||||
| 'put'
|
||||
| 'trace';
|
||||
|
||||
export type Client<
|
||||
RequestFn = never,
|
||||
Config = unknown,
|
||||
MethodFn = never,
|
||||
BuildUrlFn = never,
|
||||
SseFn = never,
|
||||
> = {
|
||||
/**
|
||||
* Returns the final request URL.
|
||||
*/
|
||||
buildUrl: BuildUrlFn;
|
||||
getConfig: () => Config;
|
||||
request: RequestFn;
|
||||
setConfig: (config: Config) => Config;
|
||||
} & {
|
||||
[K in HttpMethod]: MethodFn;
|
||||
} & ([SseFn] extends [never]
|
||||
? { sse?: never }
|
||||
: { sse: { [K in HttpMethod]: SseFn } });
|
||||
|
||||
export interface Config {
|
||||
/**
|
||||
* Auth token or a function returning auth token. The resolved value will be
|
||||
* added to the request payload as defined by its `security` array.
|
||||
*/
|
||||
auth?: ((auth: Auth) => Promise<AuthToken> | AuthToken) | AuthToken;
|
||||
/**
|
||||
* A function for serializing request body parameter. By default,
|
||||
* {@link JSON.stringify()} will be used.
|
||||
*/
|
||||
bodySerializer?: BodySerializer | null;
|
||||
/**
|
||||
* An object containing any HTTP headers that you want to pre-populate your
|
||||
* `Headers` object with.
|
||||
*
|
||||
* {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more}
|
||||
*/
|
||||
headers?:
|
||||
| RequestInit['headers']
|
||||
| Record<
|
||||
string,
|
||||
| string
|
||||
| number
|
||||
| boolean
|
||||
| (string | number | boolean)[]
|
||||
| null
|
||||
| undefined
|
||||
| unknown
|
||||
>;
|
||||
/**
|
||||
* The request method.
|
||||
*
|
||||
* {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more}
|
||||
*/
|
||||
method?: Uppercase<HttpMethod>;
|
||||
/**
|
||||
* A function for serializing request query parameters. By default, arrays
|
||||
* will be exploded in form style, objects will be exploded in deepObject
|
||||
* style, and reserved characters are percent-encoded.
|
||||
*
|
||||
* This method will have no effect if the native `paramsSerializer()` Axios
|
||||
* API function is used.
|
||||
*
|
||||
* {@link https://swagger.io/docs/specification/serialization/#query View examples}
|
||||
*/
|
||||
querySerializer?: QuerySerializer | QuerySerializerOptions;
|
||||
/**
|
||||
* A function validating request data. This is useful if you want to ensure
|
||||
* the request conforms to the desired shape, so it can be safely sent to
|
||||
* the server.
|
||||
*/
|
||||
requestValidator?: (data: unknown) => Promise<unknown>;
|
||||
/**
|
||||
* A function transforming response data before it's returned. This is useful
|
||||
* for post-processing data, e.g. converting ISO strings into Date objects.
|
||||
*/
|
||||
responseTransformer?: (data: unknown) => Promise<unknown>;
|
||||
/**
|
||||
* A function validating response data. This is useful if you want to ensure
|
||||
* the response conforms to the desired shape, so it can be safely passed to
|
||||
* the transformers and returned to the user.
|
||||
*/
|
||||
responseValidator?: (data: unknown) => Promise<unknown>;
|
||||
}
|
||||
|
||||
type IsExactlyNeverOrNeverUndefined<T> = [T] extends [never]
|
||||
? true
|
||||
: [T] extends [never | undefined]
|
||||
? [undefined] extends [T]
|
||||
? false
|
||||
: true
|
||||
: false;
|
||||
|
||||
export type OmitNever<T extends Record<string, unknown>> = {
|
||||
[K in keyof T as IsExactlyNeverOrNeverUndefined<T[K]> extends true
|
||||
? never
|
||||
: K]: T[K];
|
||||
};
|
||||
143
packages/sdk/js/src/v2/gen/core/utils.gen.ts
Normal file
143
packages/sdk/js/src/v2/gen/core/utils.gen.ts
Normal file
|
|
@ -0,0 +1,143 @@
|
|||
// This file is auto-generated by @hey-api/openapi-ts
|
||||
|
||||
import type { BodySerializer, QuerySerializer } from './bodySerializer.gen.js';
|
||||
import {
|
||||
type ArraySeparatorStyle,
|
||||
serializeArrayParam,
|
||||
serializeObjectParam,
|
||||
serializePrimitiveParam,
|
||||
} from './pathSerializer.gen.js';
|
||||
|
||||
export interface PathSerializer {
|
||||
path: Record<string, unknown>;
|
||||
url: string;
|
||||
}
|
||||
|
||||
export const PATH_PARAM_RE = /\{[^{}]+\}/g;
|
||||
|
||||
export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => {
|
||||
let url = _url;
|
||||
const matches = _url.match(PATH_PARAM_RE);
|
||||
if (matches) {
|
||||
for (const match of matches) {
|
||||
let explode = false;
|
||||
let name = match.substring(1, match.length - 1);
|
||||
let style: ArraySeparatorStyle = 'simple';
|
||||
|
||||
if (name.endsWith('*')) {
|
||||
explode = true;
|
||||
name = name.substring(0, name.length - 1);
|
||||
}
|
||||
|
||||
if (name.startsWith('.')) {
|
||||
name = name.substring(1);
|
||||
style = 'label';
|
||||
} else if (name.startsWith(';')) {
|
||||
name = name.substring(1);
|
||||
style = 'matrix';
|
||||
}
|
||||
|
||||
const value = path[name];
|
||||
|
||||
if (value === undefined || value === null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (Array.isArray(value)) {
|
||||
url = url.replace(
|
||||
match,
|
||||
serializeArrayParam({ explode, name, style, value }),
|
||||
);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (typeof value === 'object') {
|
||||
url = url.replace(
|
||||
match,
|
||||
serializeObjectParam({
|
||||
explode,
|
||||
name,
|
||||
style,
|
||||
value: value as Record<string, unknown>,
|
||||
valueOnly: true,
|
||||
}),
|
||||
);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (style === 'matrix') {
|
||||
url = url.replace(
|
||||
match,
|
||||
`;${serializePrimitiveParam({
|
||||
name,
|
||||
value: value as string,
|
||||
})}`,
|
||||
);
|
||||
continue;
|
||||
}
|
||||
|
||||
const replaceValue = encodeURIComponent(
|
||||
style === 'label' ? `.${value as string}` : (value as string),
|
||||
);
|
||||
url = url.replace(match, replaceValue);
|
||||
}
|
||||
}
|
||||
return url;
|
||||
};
|
||||
|
||||
export const getUrl = ({
|
||||
baseUrl,
|
||||
path,
|
||||
query,
|
||||
querySerializer,
|
||||
url: _url,
|
||||
}: {
|
||||
baseUrl?: string;
|
||||
path?: Record<string, unknown>;
|
||||
query?: Record<string, unknown>;
|
||||
querySerializer: QuerySerializer;
|
||||
url: string;
|
||||
}) => {
|
||||
const pathUrl = _url.startsWith('/') ? _url : `/${_url}`;
|
||||
let url = (baseUrl ?? '') + pathUrl;
|
||||
if (path) {
|
||||
url = defaultPathSerializer({ path, url });
|
||||
}
|
||||
let search = query ? querySerializer(query) : '';
|
||||
if (search.startsWith('?')) {
|
||||
search = search.substring(1);
|
||||
}
|
||||
if (search) {
|
||||
url += `?${search}`;
|
||||
}
|
||||
return url;
|
||||
};
|
||||
|
||||
export function getValidRequestBody(options: {
|
||||
body?: unknown;
|
||||
bodySerializer?: BodySerializer | null;
|
||||
serializedBody?: unknown;
|
||||
}) {
|
||||
const hasBody = options.body !== undefined;
|
||||
const isSerializedBody = hasBody && options.bodySerializer;
|
||||
|
||||
if (isSerializedBody) {
|
||||
if ('serializedBody' in options) {
|
||||
const hasSerializedBody =
|
||||
options.serializedBody !== undefined && options.serializedBody !== '';
|
||||
|
||||
return hasSerializedBody ? options.serializedBody : null;
|
||||
}
|
||||
|
||||
// not all clients implement a serializedBody property (i.e. client-axios)
|
||||
return options.body !== '' ? options.body : null;
|
||||
}
|
||||
|
||||
// plain/text body
|
||||
if (hasBody) {
|
||||
return options.body;
|
||||
}
|
||||
|
||||
// no body was provided
|
||||
return undefined;
|
||||
}
|
||||
1592
packages/sdk/js/src/v2/gen/sdk.gen.ts
Normal file
1592
packages/sdk/js/src/v2/gen/sdk.gen.ts
Normal file
File diff suppressed because it is too large
Load diff
3748
packages/sdk/js/src/v2/gen/types.gen.ts
Normal file
3748
packages/sdk/js/src/v2/gen/types.gen.ts
Normal file
File diff suppressed because it is too large
Load diff
21
packages/sdk/js/src/v2/index.ts
Normal file
21
packages/sdk/js/src/v2/index.ts
Normal file
|
|
@ -0,0 +1,21 @@
|
|||
export * from "./client.js"
|
||||
export * from "./server.js"
|
||||
|
||||
import { createOpencodeClient } from "./client.js"
|
||||
import { createOpencodeServer } from "./server.js"
|
||||
import type { ServerOptions } from "./server.js"
|
||||
|
||||
export async function createOpencode(options?: ServerOptions) {
|
||||
const server = await createOpencodeServer({
|
||||
...options,
|
||||
})
|
||||
|
||||
const client = createOpencodeClient({
|
||||
baseUrl: server.url,
|
||||
})
|
||||
|
||||
return {
|
||||
client,
|
||||
server,
|
||||
}
|
||||
}
|
||||
120
packages/sdk/js/src/v2/server.ts
Normal file
120
packages/sdk/js/src/v2/server.ts
Normal file
|
|
@ -0,0 +1,120 @@
|
|||
import { spawn } from "node:child_process"
|
||||
import { type Config } from "./gen/types.gen.js"
|
||||
|
||||
export type ServerOptions = {
|
||||
hostname?: string
|
||||
port?: number
|
||||
signal?: AbortSignal
|
||||
timeout?: number
|
||||
config?: Config
|
||||
}
|
||||
|
||||
export type TuiOptions = {
|
||||
project?: string
|
||||
model?: string
|
||||
session?: string
|
||||
agent?: string
|
||||
signal?: AbortSignal
|
||||
config?: Config
|
||||
}
|
||||
|
||||
export async function createOpencodeServer(options?: ServerOptions) {
|
||||
options = Object.assign(
|
||||
{
|
||||
hostname: "127.0.0.1",
|
||||
port: 4096,
|
||||
timeout: 5000,
|
||||
},
|
||||
options ?? {},
|
||||
)
|
||||
|
||||
const proc = spawn(`opencode`, [`serve`, `--hostname=${options.hostname}`, `--port=${options.port}`], {
|
||||
signal: options.signal,
|
||||
env: {
|
||||
...process.env,
|
||||
OPENCODE_CONFIG_CONTENT: JSON.stringify(options.config ?? {}),
|
||||
},
|
||||
})
|
||||
|
||||
const url = await new Promise<string>((resolve, reject) => {
|
||||
const id = setTimeout(() => {
|
||||
reject(new Error(`Timeout waiting for server to start after ${options.timeout}ms`))
|
||||
}, options.timeout)
|
||||
let output = ""
|
||||
proc.stdout?.on("data", (chunk) => {
|
||||
output += chunk.toString()
|
||||
const lines = output.split("\n")
|
||||
for (const line of lines) {
|
||||
if (line.startsWith("opencode server listening")) {
|
||||
const match = line.match(/on\s+(https?:\/\/[^\s]+)/)
|
||||
if (!match) {
|
||||
throw new Error(`Failed to parse server url from output: ${line}`)
|
||||
}
|
||||
clearTimeout(id)
|
||||
resolve(match[1]!)
|
||||
return
|
||||
}
|
||||
}
|
||||
})
|
||||
proc.stderr?.on("data", (chunk) => {
|
||||
output += chunk.toString()
|
||||
})
|
||||
proc.on("exit", (code) => {
|
||||
clearTimeout(id)
|
||||
let msg = `Server exited with code ${code}`
|
||||
if (output.trim()) {
|
||||
msg += `\nServer output: ${output}`
|
||||
}
|
||||
reject(new Error(msg))
|
||||
})
|
||||
proc.on("error", (error) => {
|
||||
clearTimeout(id)
|
||||
reject(error)
|
||||
})
|
||||
if (options.signal) {
|
||||
options.signal.addEventListener("abort", () => {
|
||||
clearTimeout(id)
|
||||
reject(new Error("Aborted"))
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
return {
|
||||
url,
|
||||
close() {
|
||||
proc.kill()
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
export function createOpencodeTui(options?: TuiOptions) {
|
||||
const args = []
|
||||
|
||||
if (options?.project) {
|
||||
args.push(`--project=${options.project}`)
|
||||
}
|
||||
if (options?.model) {
|
||||
args.push(`--model=${options.model}`)
|
||||
}
|
||||
if (options?.session) {
|
||||
args.push(`--session=${options.session}`)
|
||||
}
|
||||
if (options?.agent) {
|
||||
args.push(`--agent=${options.agent}`)
|
||||
}
|
||||
|
||||
const proc = spawn(`opencode`, args, {
|
||||
signal: options?.signal,
|
||||
stdio: "inherit",
|
||||
env: {
|
||||
...process.env,
|
||||
OPENCODE_CONFIG_CONTENT: JSON.stringify(options?.config ?? {}),
|
||||
},
|
||||
})
|
||||
|
||||
return {
|
||||
close() {
|
||||
proc.kill()
|
||||
},
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue