mirror of
https://github.com/aljazceru/opencode.git
synced 2025-12-23 18:54:21 +01:00
wip: plugins
This commit is contained in:
13
bun.lock
13
bun.lock
@@ -38,6 +38,7 @@
|
|||||||
"@octokit/graphql": "9.0.1",
|
"@octokit/graphql": "9.0.1",
|
||||||
"@octokit/rest": "22.0.0",
|
"@octokit/rest": "22.0.0",
|
||||||
"@openauthjs/openauth": "0.4.3",
|
"@openauthjs/openauth": "0.4.3",
|
||||||
|
"@opencode-ai/plugin": "workspace:*",
|
||||||
"@standard-schema/spec": "1.0.0",
|
"@standard-schema/spec": "1.0.0",
|
||||||
"@zip.js/zip.js": "2.7.62",
|
"@zip.js/zip.js": "2.7.62",
|
||||||
"ai": "catalog:",
|
"ai": "catalog:",
|
||||||
@@ -74,6 +75,16 @@
|
|||||||
"zod-to-json-schema": "3.24.5",
|
"zod-to-json-schema": "3.24.5",
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
"packages/plugin": {
|
||||||
|
"name": "@opencode-ai/plugin",
|
||||||
|
"version": "0.0.0",
|
||||||
|
"devDependencies": {
|
||||||
|
"@hey-api/openapi-ts": "0.80.1",
|
||||||
|
"@opencode-ai/sdk": "workspace:*",
|
||||||
|
"@tsconfig/node22": "catalog:",
|
||||||
|
"typescript": "catalog:",
|
||||||
|
},
|
||||||
|
},
|
||||||
"packages/sdk/js": {
|
"packages/sdk/js": {
|
||||||
"name": "@opencode-ai/sdk",
|
"name": "@opencode-ai/sdk",
|
||||||
"version": "0.0.0",
|
"version": "0.0.0",
|
||||||
@@ -416,6 +427,8 @@
|
|||||||
|
|
||||||
"@openauthjs/openauth": ["@openauthjs/openauth@0.4.3", "", { "dependencies": { "@standard-schema/spec": "1.0.0-beta.3", "aws4fetch": "1.0.20", "jose": "5.9.6" }, "peerDependencies": { "arctic": "^2.2.2", "hono": "^4.0.0" } }, "sha512-RlnjqvHzqcbFVymEwhlUEuac4utA5h4nhSK/i2szZuQmxTIqbGUxZ+nM+avM+VV4Ing+/ZaNLKILoXS3yrkOOw=="],
|
"@openauthjs/openauth": ["@openauthjs/openauth@0.4.3", "", { "dependencies": { "@standard-schema/spec": "1.0.0-beta.3", "aws4fetch": "1.0.20", "jose": "5.9.6" }, "peerDependencies": { "arctic": "^2.2.2", "hono": "^4.0.0" } }, "sha512-RlnjqvHzqcbFVymEwhlUEuac4utA5h4nhSK/i2szZuQmxTIqbGUxZ+nM+avM+VV4Ing+/ZaNLKILoXS3yrkOOw=="],
|
||||||
|
|
||||||
|
"@opencode-ai/plugin": ["@opencode-ai/plugin@workspace:packages/plugin"],
|
||||||
|
|
||||||
"@opencode-ai/sdk": ["@opencode-ai/sdk@workspace:packages/sdk/js"],
|
"@opencode-ai/sdk": ["@opencode-ai/sdk@workspace:packages/sdk/js"],
|
||||||
|
|
||||||
"@opencode/function": ["@opencode/function@workspace:packages/function"],
|
"@opencode/function": ["@opencode/function@workspace:packages/function"],
|
||||||
|
|||||||
@@ -1,16 +1,6 @@
|
|||||||
{
|
{
|
||||||
"$schema": "https://opencode.ai/config.json",
|
"$schema": "https://opencode.ai/config.json",
|
||||||
"provider": {
|
"plugin": ["./packages/plugin/src/example.ts"],
|
||||||
"cerebras": {
|
|
||||||
"options": {
|
|
||||||
"apiKey": "csk-m33xrvt43whkypn8r4ph9xc8fenhx2f68c3pj22ext45v5k9"
|
|
||||||
},
|
|
||||||
"npm": "@ai-sdk/cerebras",
|
|
||||||
"models": {
|
|
||||||
"qwen-3-coder-480b": {}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"mcp": {
|
"mcp": {
|
||||||
"context7": {
|
"context7": {
|
||||||
"type": "remote",
|
"type": "remote",
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@opencode/function",
|
"name": "@opencode/function",
|
||||||
"version": "0.0.1",
|
"version": "0.0.0-202508022246",
|
||||||
"$schema": "https://json.schemastore.org/package.json",
|
"$schema": "https://json.schemastore.org/package.json",
|
||||||
"private": true,
|
"private": true,
|
||||||
"type": "module",
|
"type": "module",
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"$schema": "https://json.schemastore.org/package.json",
|
"$schema": "https://json.schemastore.org/package.json",
|
||||||
"version": "0.0.0",
|
"version": "0.0.0-202508022246",
|
||||||
"name": "opencode",
|
"name": "opencode",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"private": true,
|
"private": true,
|
||||||
@@ -36,6 +36,7 @@
|
|||||||
"@octokit/graphql": "9.0.1",
|
"@octokit/graphql": "9.0.1",
|
||||||
"@octokit/rest": "22.0.0",
|
"@octokit/rest": "22.0.0",
|
||||||
"@openauthjs/openauth": "0.4.3",
|
"@openauthjs/openauth": "0.4.3",
|
||||||
|
"@opencode-ai/plugin": "workspace:*",
|
||||||
"@standard-schema/spec": "1.0.0",
|
"@standard-schema/spec": "1.0.0",
|
||||||
"@zip.js/zip.js": "2.7.62",
|
"@zip.js/zip.js": "2.7.62",
|
||||||
"ai": "catalog:",
|
"ai": "catalog:",
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ import { App } from "../app/app"
|
|||||||
import { ConfigHooks } from "../config/hooks"
|
import { ConfigHooks } from "../config/hooks"
|
||||||
import { Format } from "../format"
|
import { Format } from "../format"
|
||||||
import { LSP } from "../lsp"
|
import { LSP } from "../lsp"
|
||||||
|
import { Plugin } from "../plugin"
|
||||||
import { Share } from "../share/share"
|
import { Share } from "../share/share"
|
||||||
import { Snapshot } from "../snapshot"
|
import { Snapshot } from "../snapshot"
|
||||||
|
|
||||||
@@ -9,6 +10,7 @@ export async function bootstrap<T>(input: App.Input, cb: (app: App.Info) => Prom
|
|||||||
return App.provide(input, async (app) => {
|
return App.provide(input, async (app) => {
|
||||||
Share.init()
|
Share.init()
|
||||||
Format.init()
|
Format.init()
|
||||||
|
Plugin.init()
|
||||||
ConfigHooks.init()
|
ConfigHooks.init()
|
||||||
LSP.init()
|
LSP.init()
|
||||||
Snapshot.init()
|
Snapshot.init()
|
||||||
|
|||||||
@@ -23,13 +23,13 @@ export namespace Config {
|
|||||||
for (const file of ["opencode.jsonc", "opencode.json"]) {
|
for (const file of ["opencode.jsonc", "opencode.json"]) {
|
||||||
const found = await Filesystem.findUp(file, app.path.cwd, app.path.root)
|
const found = await Filesystem.findUp(file, app.path.cwd, app.path.root)
|
||||||
for (const resolved of found.toReversed()) {
|
for (const resolved of found.toReversed()) {
|
||||||
result = mergeDeep(result, await load(resolved))
|
result = mergeDeep(result, await loadFile(resolved))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Override with custom config if provided
|
// Override with custom config if provided
|
||||||
if (Flag.OPENCODE_CONFIG) {
|
if (Flag.OPENCODE_CONFIG) {
|
||||||
result = mergeDeep(result, await load(Flag.OPENCODE_CONFIG))
|
result = mergeDeep(result, await loadFile(Flag.OPENCODE_CONFIG))
|
||||||
log.debug("loaded custom config", { path: Flag.OPENCODE_CONFIG })
|
log.debug("loaded custom config", { path: Flag.OPENCODE_CONFIG })
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -37,7 +37,7 @@ export namespace Config {
|
|||||||
if (value.type === "wellknown") {
|
if (value.type === "wellknown") {
|
||||||
process.env[value.key] = value.token
|
process.env[value.key] = value.token
|
||||||
const wellknown = await fetch(`${key}/.well-known/opencode`).then((x) => x.json())
|
const wellknown = await fetch(`${key}/.well-known/opencode`).then((x) => x.json())
|
||||||
result = mergeDeep(result, await loadRaw(JSON.stringify(wellknown.config ?? {}), process.cwd()))
|
result = mergeDeep(result, await load(JSON.stringify(wellknown.config ?? {}), process.cwd()))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -223,6 +223,7 @@ export namespace Config {
|
|||||||
$schema: z.string().optional().describe("JSON schema reference for configuration validation"),
|
$schema: z.string().optional().describe("JSON schema reference for configuration validation"),
|
||||||
theme: z.string().optional().describe("Theme name to use for the interface"),
|
theme: z.string().optional().describe("Theme name to use for the interface"),
|
||||||
keybinds: Keybinds.optional().describe("Custom keybind configurations"),
|
keybinds: Keybinds.optional().describe("Custom keybind configurations"),
|
||||||
|
plugin: z.string().array().optional(),
|
||||||
share: z
|
share: z
|
||||||
.enum(["manual", "auto", "disabled"])
|
.enum(["manual", "auto", "disabled"])
|
||||||
.optional()
|
.optional()
|
||||||
@@ -352,9 +353,9 @@ export namespace Config {
|
|||||||
export const global = lazy(async () => {
|
export const global = lazy(async () => {
|
||||||
let result: Info = pipe(
|
let result: Info = pipe(
|
||||||
{},
|
{},
|
||||||
mergeDeep(await load(path.join(Global.Path.config, "config.json"))),
|
mergeDeep(await loadFile(path.join(Global.Path.config, "config.json"))),
|
||||||
mergeDeep(await load(path.join(Global.Path.config, "opencode.json"))),
|
mergeDeep(await loadFile(path.join(Global.Path.config, "opencode.json"))),
|
||||||
mergeDeep(await load(path.join(Global.Path.config, "opencode.jsonc"))),
|
mergeDeep(await loadFile(path.join(Global.Path.config, "opencode.jsonc"))),
|
||||||
)
|
)
|
||||||
|
|
||||||
await import(path.join(Global.Path.config, "config"), {
|
await import(path.join(Global.Path.config, "config"), {
|
||||||
@@ -375,25 +376,26 @@ export namespace Config {
|
|||||||
return result
|
return result
|
||||||
})
|
})
|
||||||
|
|
||||||
async function load(configPath: string): Promise<Info> {
|
async function loadFile(filepath: string): Promise<Info> {
|
||||||
let text = await Bun.file(configPath)
|
log.info("loading", { path: filepath })
|
||||||
|
let text = await Bun.file(filepath)
|
||||||
.text()
|
.text()
|
||||||
.catch((err) => {
|
.catch((err) => {
|
||||||
if (err.code === "ENOENT") return
|
if (err.code === "ENOENT") return
|
||||||
throw new JsonError({ path: configPath }, { cause: err })
|
throw new JsonError({ path: filepath }, { cause: err })
|
||||||
})
|
})
|
||||||
if (!text) return {}
|
if (!text) return {}
|
||||||
return loadRaw(text, configPath)
|
return load(text, filepath)
|
||||||
}
|
}
|
||||||
|
|
||||||
async function loadRaw(text: string, configPath: string) {
|
async function load(text: string, filepath: string) {
|
||||||
text = text.replace(/\{env:([^}]+)\}/g, (_, varName) => {
|
text = text.replace(/\{env:([^}]+)\}/g, (_, varName) => {
|
||||||
return process.env[varName] || ""
|
return process.env[varName] || ""
|
||||||
})
|
})
|
||||||
|
|
||||||
const fileMatches = text.match(/\{file:[^}]+\}/g)
|
const fileMatches = text.match(/\{file:[^}]+\}/g)
|
||||||
if (fileMatches) {
|
if (fileMatches) {
|
||||||
const configDir = path.dirname(configPath)
|
const configDir = path.dirname(filepath)
|
||||||
const lines = text.split("\n")
|
const lines = text.split("\n")
|
||||||
|
|
||||||
for (const match of fileMatches) {
|
for (const match of fileMatches) {
|
||||||
@@ -428,7 +430,7 @@ export namespace Config {
|
|||||||
.join("\n")
|
.join("\n")
|
||||||
|
|
||||||
throw new JsonError({
|
throw new JsonError({
|
||||||
path: configPath,
|
path: filepath,
|
||||||
message: `\n--- JSONC Input ---\n${text}\n--- Errors ---\n${errorDetails}\n--- End ---`,
|
message: `\n--- JSONC Input ---\n${text}\n--- Errors ---\n${errorDetails}\n--- End ---`,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@@ -437,11 +439,21 @@ export namespace Config {
|
|||||||
if (parsed.success) {
|
if (parsed.success) {
|
||||||
if (!parsed.data.$schema) {
|
if (!parsed.data.$schema) {
|
||||||
parsed.data.$schema = "https://opencode.ai/config.json"
|
parsed.data.$schema = "https://opencode.ai/config.json"
|
||||||
await Bun.write(configPath, JSON.stringify(parsed.data, null, 2))
|
await Bun.write(filepath, JSON.stringify(parsed.data, null, 2))
|
||||||
}
|
}
|
||||||
return parsed.data
|
const data = parsed.data
|
||||||
|
if (data.plugin) {
|
||||||
|
for (let i = 0; i < data.plugin?.length; i++) {
|
||||||
|
const plugin = data.plugin[i]
|
||||||
|
if (typeof plugin === "string") {
|
||||||
|
data.plugin[i] = path.resolve(path.dirname(filepath), plugin)
|
||||||
}
|
}
|
||||||
throw new InvalidError({ path: configPath, issues: parsed.error.issues })
|
}
|
||||||
|
}
|
||||||
|
return data
|
||||||
|
}
|
||||||
|
|
||||||
|
throw new InvalidError({ path: filepath, issues: parsed.error.issues })
|
||||||
}
|
}
|
||||||
export const JsonError = NamedError.create(
|
export const JsonError = NamedError.create(
|
||||||
"ConfigJsonError",
|
"ConfigJsonError",
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ import { z } from "zod"
|
|||||||
import { Bus } from "../bus"
|
import { Bus } from "../bus"
|
||||||
import { Log } from "../util/log"
|
import { Log } from "../util/log"
|
||||||
import { Identifier } from "../id/id"
|
import { Identifier } from "../id/id"
|
||||||
|
import { Plugin } from "../plugin"
|
||||||
|
|
||||||
export namespace Permission {
|
export namespace Permission {
|
||||||
const log = Log.create({ service: "permission" })
|
const log = Log.create({ service: "permission" })
|
||||||
@@ -67,7 +68,7 @@ export namespace Permission {
|
|||||||
},
|
},
|
||||||
)
|
)
|
||||||
|
|
||||||
export function ask(input: {
|
export async function ask(input: {
|
||||||
type: Info["type"]
|
type: Info["type"]
|
||||||
title: Info["title"]
|
title: Info["title"]
|
||||||
pattern?: Info["pattern"]
|
pattern?: Info["pattern"]
|
||||||
@@ -95,6 +96,18 @@ export namespace Permission {
|
|||||||
created: Date.now(),
|
created: Date.now(),
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
|
switch (
|
||||||
|
await Plugin.trigger("permission.ask", info, {
|
||||||
|
status: "ask",
|
||||||
|
}).then((x) => x.status)
|
||||||
|
) {
|
||||||
|
case "deny":
|
||||||
|
throw new RejectedError(info.sessionID, info.id, info.callID)
|
||||||
|
case "allow":
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
pending[input.sessionID] = pending[input.sessionID] || {}
|
pending[input.sessionID] = pending[input.sessionID] || {}
|
||||||
return new Promise<void>((resolve, reject) => {
|
return new Promise<void>((resolve, reject) => {
|
||||||
pending[input.sessionID][info.id] = {
|
pending[input.sessionID][info.id] = {
|
||||||
|
|||||||
85
packages/opencode/src/plugin/index.ts
Normal file
85
packages/opencode/src/plugin/index.ts
Normal file
@@ -0,0 +1,85 @@
|
|||||||
|
import type { Hooks, Plugin as PluginInstance } from "@opencode-ai/plugin"
|
||||||
|
import { App } from "../app/app"
|
||||||
|
import { Config } from "../config/config"
|
||||||
|
import { Bus } from "../bus"
|
||||||
|
import { Log } from "../util/log"
|
||||||
|
import { createOpencodeClient } from "@opencode-ai/sdk"
|
||||||
|
import { Server } from "../server/server"
|
||||||
|
import { pathOr } from "remeda"
|
||||||
|
|
||||||
|
export namespace Plugin {
|
||||||
|
const log = Log.create({ service: "plugin" })
|
||||||
|
|
||||||
|
const state = App.state("plugin", async (app) => {
|
||||||
|
const client = createOpencodeClient({
|
||||||
|
baseUrl: "http://localhost:4096",
|
||||||
|
fetch: async (...args) => Server.app().fetch(...args),
|
||||||
|
})
|
||||||
|
const config = await Config.get()
|
||||||
|
const hooks = []
|
||||||
|
for (const plugin of config.plugin ?? []) {
|
||||||
|
log.info("loading plugin", { path: plugin })
|
||||||
|
const mod = await import(plugin)
|
||||||
|
for (const [_name, fn] of Object.entries<PluginInstance>(mod)) {
|
||||||
|
const init = await fn({
|
||||||
|
client,
|
||||||
|
app,
|
||||||
|
$: Bun.$,
|
||||||
|
})
|
||||||
|
hooks.push(init)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
hooks,
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
type Path<T, Prefix extends string = ""> = T extends object
|
||||||
|
? {
|
||||||
|
[K in keyof T]: K extends string
|
||||||
|
? T[K] extends Function | undefined
|
||||||
|
? `${Prefix}${K}`
|
||||||
|
: Path<T[K], `${Prefix}${K}.`>
|
||||||
|
: never
|
||||||
|
}[keyof T]
|
||||||
|
: never
|
||||||
|
|
||||||
|
export type FunctionFromKey<T, P extends Path<T>> = P extends `${infer K}.${infer R}`
|
||||||
|
? K extends keyof T
|
||||||
|
? R extends Path<T[K]>
|
||||||
|
? FunctionFromKey<T[K], R>
|
||||||
|
: never
|
||||||
|
: never
|
||||||
|
: P extends keyof T
|
||||||
|
? T[P]
|
||||||
|
: never
|
||||||
|
|
||||||
|
export async function trigger<
|
||||||
|
Name extends Path<Required<Hooks>>,
|
||||||
|
Input = Parameters<FunctionFromKey<Required<Hooks>, Name>>[0],
|
||||||
|
Output = Parameters<FunctionFromKey<Required<Hooks>, Name>>[1],
|
||||||
|
>(fn: Name, input: Input, output: Output): Promise<Output> {
|
||||||
|
if (!fn) return output
|
||||||
|
const path = fn.split(".")
|
||||||
|
for (const hook of await state().then((x) => x.hooks)) {
|
||||||
|
// @ts-expect-error
|
||||||
|
const fn = pathOr(hook, path, undefined)
|
||||||
|
if (!fn) continue
|
||||||
|
// @ts-expect-error
|
||||||
|
await fn(input, output)
|
||||||
|
}
|
||||||
|
return output
|
||||||
|
}
|
||||||
|
|
||||||
|
export function init() {
|
||||||
|
Bus.subscribeAll(async (input) => {
|
||||||
|
const hooks = await state().then((x) => x.hooks)
|
||||||
|
for (const hook of hooks) {
|
||||||
|
hook["event"]?.({
|
||||||
|
event: input,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -97,7 +97,7 @@ export namespace Provider {
|
|||||||
Array.isArray(msg.content) && msg.content.some((part: any) => part.type === "image_url"),
|
Array.isArray(msg.content) && msg.content.some((part: any) => part.type === "image_url"),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
} catch { }
|
} catch {}
|
||||||
const headers: Record<string, string> = {
|
const headers: Record<string, string> = {
|
||||||
...init.headers,
|
...init.headers,
|
||||||
...copilot.HEADERS,
|
...copilot.HEADERS,
|
||||||
@@ -386,6 +386,10 @@ export namespace Provider {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export async function getProvider(providerID: string) {
|
||||||
|
return state().then((s) => s.providers[providerID])
|
||||||
|
}
|
||||||
|
|
||||||
export async function getModel(providerID: string, modelID: string) {
|
export async function getModel(providerID: string, modelID: string) {
|
||||||
const key = `${providerID}/${modelID}`
|
const key = `${providerID}/${modelID}`
|
||||||
const s = await state()
|
const s = await state()
|
||||||
|
|||||||
@@ -19,6 +19,7 @@ import { MessageV2 } from "../session/message-v2"
|
|||||||
import { Mode } from "../session/mode"
|
import { Mode } from "../session/mode"
|
||||||
import { callTui, TuiRoute } from "./tui"
|
import { callTui, TuiRoute } from "./tui"
|
||||||
import { Permission } from "../permission"
|
import { Permission } from "../permission"
|
||||||
|
import { lazy } from "../util/lazy"
|
||||||
|
|
||||||
const ERRORS = {
|
const ERRORS = {
|
||||||
400: {
|
400: {
|
||||||
@@ -48,7 +49,7 @@ export namespace Server {
|
|||||||
Connected: Bus.event("server.connected", z.object({})),
|
Connected: Bus.event("server.connected", z.object({})),
|
||||||
}
|
}
|
||||||
|
|
||||||
function app() {
|
export const app = lazy(() => {
|
||||||
const app = new Hono()
|
const app = new Hono()
|
||||||
|
|
||||||
const result = app
|
const result = app
|
||||||
@@ -1022,7 +1023,7 @@ export namespace Server {
|
|||||||
.route("/tui/control", TuiRoute)
|
.route("/tui/control", TuiRoute)
|
||||||
|
|
||||||
return result
|
return result
|
||||||
}
|
})
|
||||||
|
|
||||||
export async function openapi() {
|
export async function openapi() {
|
||||||
const a = app()
|
const a = app()
|
||||||
|
|||||||
@@ -41,6 +41,7 @@ import { LSP } from "../lsp"
|
|||||||
import { ReadTool } from "../tool/read"
|
import { ReadTool } from "../tool/read"
|
||||||
import { mergeDeep, pipe, splitWhen } from "remeda"
|
import { mergeDeep, pipe, splitWhen } from "remeda"
|
||||||
import { ToolRegistry } from "../tool/registry"
|
import { ToolRegistry } from "../tool/registry"
|
||||||
|
import { Plugin } from "../plugin"
|
||||||
|
|
||||||
export namespace Session {
|
export namespace Session {
|
||||||
const log = Log.create({ service: "session" })
|
const log = Log.create({ service: "session" })
|
||||||
@@ -571,7 +572,14 @@ export namespace Session {
|
|||||||
text: PROMPT_PLAN,
|
text: PROMPT_PLAN,
|
||||||
synthetic: true,
|
synthetic: true,
|
||||||
})
|
})
|
||||||
|
await Plugin.trigger(
|
||||||
|
"chat.message",
|
||||||
|
{},
|
||||||
|
{
|
||||||
|
message: userMsg,
|
||||||
|
parts: userParts,
|
||||||
|
},
|
||||||
|
)
|
||||||
await updateMessage(userMsg)
|
await updateMessage(userMsg)
|
||||||
for (const part of userParts) {
|
for (const part of userParts) {
|
||||||
await updatePart(part)
|
await updatePart(part)
|
||||||
@@ -716,6 +724,17 @@ export namespace Session {
|
|||||||
description: item.description,
|
description: item.description,
|
||||||
inputSchema: item.parameters as ZodSchema,
|
inputSchema: item.parameters as ZodSchema,
|
||||||
async execute(args, options) {
|
async execute(args, options) {
|
||||||
|
await Plugin.trigger(
|
||||||
|
"tool.execute.before",
|
||||||
|
{
|
||||||
|
tool: item.id,
|
||||||
|
sessionID: input.sessionID,
|
||||||
|
callID: options.toolCallId,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
args,
|
||||||
|
},
|
||||||
|
)
|
||||||
await processor.track(options.toolCallId)
|
await processor.track(options.toolCallId)
|
||||||
const result = await item.execute(args, {
|
const result = await item.execute(args, {
|
||||||
sessionID: input.sessionID,
|
sessionID: input.sessionID,
|
||||||
@@ -740,6 +759,15 @@ export namespace Session {
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
|
await Plugin.trigger(
|
||||||
|
"tool.execute.after",
|
||||||
|
{
|
||||||
|
tool: item.id,
|
||||||
|
sessionID: input.sessionID,
|
||||||
|
callID: options.toolCallId,
|
||||||
|
},
|
||||||
|
result,
|
||||||
|
)
|
||||||
return result
|
return result
|
||||||
},
|
},
|
||||||
toModelOutput(result) {
|
toModelOutput(result) {
|
||||||
@@ -776,6 +804,21 @@ export namespace Session {
|
|||||||
tools[key] = item
|
tools[key] = item
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const params = {
|
||||||
|
temperature: model.info.temperature
|
||||||
|
? (mode.temperature ?? ProviderTransform.temperature(input.providerID, input.modelID))
|
||||||
|
: undefined,
|
||||||
|
topP: mode.topP ?? ProviderTransform.topP(input.providerID, input.modelID),
|
||||||
|
}
|
||||||
|
await Plugin.trigger(
|
||||||
|
"chat.params",
|
||||||
|
{
|
||||||
|
model: model.info,
|
||||||
|
provider: await Provider.getProvider(input.providerID),
|
||||||
|
message: userMsg,
|
||||||
|
},
|
||||||
|
params,
|
||||||
|
)
|
||||||
const stream = streamText({
|
const stream = streamText({
|
||||||
onError(e) {
|
onError(e) {
|
||||||
log.error("streamText error", {
|
log.error("streamText error", {
|
||||||
@@ -835,6 +878,8 @@ export namespace Session {
|
|||||||
providerOptions: {
|
providerOptions: {
|
||||||
[input.providerID]: model.info.options,
|
[input.providerID]: model.info.options,
|
||||||
},
|
},
|
||||||
|
temperature: params.temperature,
|
||||||
|
topP: params.topP,
|
||||||
messages: [
|
messages: [
|
||||||
...system.map(
|
...system.map(
|
||||||
(x): ModelMessage => ({
|
(x): ModelMessage => ({
|
||||||
@@ -844,10 +889,6 @@ export namespace Session {
|
|||||||
),
|
),
|
||||||
...MessageV2.toModelMessage(msgs),
|
...MessageV2.toModelMessage(msgs),
|
||||||
],
|
],
|
||||||
temperature: model.info.temperature
|
|
||||||
? (mode.temperature ?? ProviderTransform.temperature(input.providerID, input.modelID))
|
|
||||||
: undefined,
|
|
||||||
topP: mode.topP ?? ProviderTransform.topP(input.providerID, input.modelID),
|
|
||||||
tools: model.info.tool_call === false ? undefined : tools,
|
tools: model.info.tool_call === false ? undefined : tools,
|
||||||
model: wrapLanguageModel({
|
model: wrapLanguageModel({
|
||||||
model: model.language,
|
model: model.language,
|
||||||
|
|||||||
@@ -1,5 +1,9 @@
|
|||||||
{
|
{
|
||||||
"$schema": "https://json.schemastore.org/tsconfig",
|
"$schema": "https://json.schemastore.org/tsconfig",
|
||||||
"extends": "@tsconfig/bun/tsconfig.json",
|
"extends": "@tsconfig/bun/tsconfig.json",
|
||||||
"compilerOptions": {}
|
"compilerOptions": {
|
||||||
|
"customConditions": [
|
||||||
|
"development"
|
||||||
|
]
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
1
packages/plugin/.gitignore
vendored
Normal file
1
packages/plugin/.gitignore
vendored
Normal file
@@ -0,0 +1 @@
|
|||||||
|
dist
|
||||||
21
packages/plugin/package.json
Normal file
21
packages/plugin/package.json
Normal file
@@ -0,0 +1,21 @@
|
|||||||
|
{
|
||||||
|
"$schema": "https://json.schemastore.org/package.json",
|
||||||
|
"name": "@opencode-ai/plugin",
|
||||||
|
"version": "0.0.0",
|
||||||
|
"type": "module",
|
||||||
|
"scripts": {
|
||||||
|
"typecheck": "tsc --noEmit"
|
||||||
|
},
|
||||||
|
"exports": {
|
||||||
|
".": "./src/index.ts"
|
||||||
|
},
|
||||||
|
"files": [
|
||||||
|
"dist"
|
||||||
|
],
|
||||||
|
"devDependencies": {
|
||||||
|
"typescript": "catalog:",
|
||||||
|
"@hey-api/openapi-ts": "0.80.1",
|
||||||
|
"@tsconfig/node22": "catalog:",
|
||||||
|
"@opencode-ai/sdk": "workspace:*"
|
||||||
|
}
|
||||||
|
}
|
||||||
18
packages/plugin/script/publish.ts
Normal file
18
packages/plugin/script/publish.ts
Normal file
@@ -0,0 +1,18 @@
|
|||||||
|
#!/usr/bin/env bun
|
||||||
|
|
||||||
|
const dir = new URL("..", import.meta.url).pathname
|
||||||
|
process.chdir(dir)
|
||||||
|
|
||||||
|
import { $ } from "bun"
|
||||||
|
|
||||||
|
const snapshot = process.env["OPENCODE_SNAPSHOT"] === "true"
|
||||||
|
|
||||||
|
await $`bun tsc`
|
||||||
|
|
||||||
|
if (snapshot) {
|
||||||
|
await $`bun publish --tag snapshot --access public`
|
||||||
|
await $`git checkout package.json`
|
||||||
|
}
|
||||||
|
if (!snapshot) {
|
||||||
|
await $`bun publish --access public`
|
||||||
|
}
|
||||||
7
packages/plugin/src/example.ts
Normal file
7
packages/plugin/src/example.ts
Normal file
@@ -0,0 +1,7 @@
|
|||||||
|
import { Plugin } from "./index"
|
||||||
|
|
||||||
|
export const ExamplePlugin: Plugin = async ({ app, client }) => {
|
||||||
|
return {
|
||||||
|
permission: {},
|
||||||
|
}
|
||||||
|
}
|
||||||
56
packages/plugin/src/index.ts
Normal file
56
packages/plugin/src/index.ts
Normal file
@@ -0,0 +1,56 @@
|
|||||||
|
import type { Event, createOpencodeClient, App, Model, Provider, Permission, UserMessage, Part } from "@opencode-ai/sdk"
|
||||||
|
import { $ } from "bun"
|
||||||
|
|
||||||
|
export type PluginInput = {
|
||||||
|
client: ReturnType<typeof createOpencodeClient>
|
||||||
|
app: App
|
||||||
|
$: $
|
||||||
|
}
|
||||||
|
export type Plugin = (input: PluginInput) => Promise<Hooks>
|
||||||
|
|
||||||
|
export interface Hooks {
|
||||||
|
event?: (input: { event: Event }) => Promise<void>
|
||||||
|
chat?: {
|
||||||
|
/**
|
||||||
|
* Called when a new message is received
|
||||||
|
*/
|
||||||
|
message?: (input: {}, output: { message: UserMessage; parts: Part[] }) => Promise<void>
|
||||||
|
/**
|
||||||
|
* Modify parameters sent to LLM
|
||||||
|
*/
|
||||||
|
params?: (
|
||||||
|
input: { model: Model; provider: Provider; message: UserMessage },
|
||||||
|
output: { temperature: number; topP: number },
|
||||||
|
) => Promise<void>
|
||||||
|
}
|
||||||
|
permission?: {
|
||||||
|
/**
|
||||||
|
* Called when a permission is asked
|
||||||
|
*/
|
||||||
|
ask?: (input: Permission, output: { status: "ask" | "deny" | "allow" }) => Promise<void>
|
||||||
|
}
|
||||||
|
tool?: {
|
||||||
|
execute?: {
|
||||||
|
/**
|
||||||
|
* Called before a tool is executed
|
||||||
|
*/
|
||||||
|
before?: (
|
||||||
|
input: { tool: string; sessionID: string; callID: string },
|
||||||
|
output: {
|
||||||
|
args: any
|
||||||
|
},
|
||||||
|
) => Promise<void>
|
||||||
|
/**
|
||||||
|
* Called after a tool is executed
|
||||||
|
*/
|
||||||
|
after?: (
|
||||||
|
input: { tool: string; sessionID: string; callID: string },
|
||||||
|
output: {
|
||||||
|
title: string
|
||||||
|
output: string
|
||||||
|
metadata: any
|
||||||
|
},
|
||||||
|
) => Promise<void>
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
16
packages/plugin/tsconfig.json
Normal file
16
packages/plugin/tsconfig.json
Normal file
@@ -0,0 +1,16 @@
|
|||||||
|
{
|
||||||
|
"$schema": "https://json.schemastore.org/tsconfig.json",
|
||||||
|
"extends": "@tsconfig/node22/tsconfig.json",
|
||||||
|
"compilerOptions": {
|
||||||
|
"outDir": "dist",
|
||||||
|
"module": "preserve",
|
||||||
|
"declaration": true,
|
||||||
|
"moduleResolution": "bundler",
|
||||||
|
"customConditions": [
|
||||||
|
"development"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"include": [
|
||||||
|
"src"
|
||||||
|
]
|
||||||
|
}
|
||||||
@@ -1,10 +1,16 @@
|
|||||||
{
|
{
|
||||||
"$schema": "https://json.schemastore.org/package.json",
|
"$schema": "https://json.schemastore.org/package.json",
|
||||||
"name": "@opencode-ai/sdk",
|
"name": "@opencode-ai/sdk",
|
||||||
"version": "0.0.0",
|
"version": "0.0.0-202508022246",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
|
"scripts": {
|
||||||
|
"typecheck": "tsc --noEmit"
|
||||||
|
},
|
||||||
"exports": {
|
"exports": {
|
||||||
".": "./dist/index.js"
|
".": {
|
||||||
|
"development": "./src/index.ts",
|
||||||
|
"import": "./dist/index.js"
|
||||||
|
}
|
||||||
},
|
},
|
||||||
"files": [
|
"files": [
|
||||||
"dist"
|
"dist"
|
||||||
|
|||||||
@@ -36,6 +36,7 @@ await createClient({
|
|||||||
},
|
},
|
||||||
],
|
],
|
||||||
})
|
})
|
||||||
|
await $`bun prettier --write src/gen`
|
||||||
|
|
||||||
await $`rm -rf dist`
|
await $`rm -rf dist`
|
||||||
await $`bun tsc`
|
await $`bun tsc`
|
||||||
|
|||||||
@@ -5,20 +5,13 @@ process.chdir(dir)
|
|||||||
|
|
||||||
import { $ } from "bun"
|
import { $ } from "bun"
|
||||||
|
|
||||||
const version = process.env["OPENCODE_VERSION"]
|
|
||||||
if (!version) {
|
|
||||||
throw new Error("OPENCODE_VERSION is required")
|
|
||||||
}
|
|
||||||
|
|
||||||
await import("./generate")
|
await import("./generate")
|
||||||
|
|
||||||
const snapshot = process.env["OPENCODE_SNAPSHOT"] === "true"
|
const snapshot = process.env["OPENCODE_SNAPSHOT"] === "true"
|
||||||
|
|
||||||
await $`bun pm version --allow-same-version --no-git-tag-version ${version}`
|
|
||||||
if (snapshot) {
|
if (snapshot) {
|
||||||
await $`bun publish --tag snapshot`
|
await $`bun publish --tag snapshot`
|
||||||
}
|
}
|
||||||
if (!snapshot) {
|
if (!snapshot) {
|
||||||
await $`bun publish`
|
await $`bun publish`
|
||||||
}
|
}
|
||||||
await $`bun pm version 0.0.0 --no-git-tag-version`
|
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
// This file is auto-generated by @hey-api/openapi-ts
|
// This file is auto-generated by @hey-api/openapi-ts
|
||||||
|
|
||||||
import type { ClientOptions } from './types.gen';
|
import type { ClientOptions } from "./types.gen"
|
||||||
import { type Config, type ClientOptions as DefaultClientOptions, createClient, createConfig } from './client';
|
import { type Config, type ClientOptions as DefaultClientOptions, createClient, createConfig } from "./client"
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The `createClientConfig()` function will be called on client initialization
|
* The `createClientConfig()` function will be called on client initialization
|
||||||
@@ -11,8 +11,12 @@ import { type Config, type ClientOptions as DefaultClientOptions, createClient,
|
|||||||
* `setConfig()`. This is useful for example if you're using Next.js
|
* `setConfig()`. This is useful for example if you're using Next.js
|
||||||
* to ensure your client always has the correct values.
|
* 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 DefaultClientOptions = ClientOptions> = (
|
||||||
|
override?: Config<DefaultClientOptions & T>,
|
||||||
|
) => Config<Required<DefaultClientOptions> & T>
|
||||||
|
|
||||||
export const client = createClient(createConfig<ClientOptions>({
|
export const client = createClient(
|
||||||
baseUrl: 'http://localhost:4096'
|
createConfig<ClientOptions>({
|
||||||
}));
|
baseUrl: "http://localhost:4096",
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import type { Client, Config, RequestOptions } from './types';
|
import type { Client, Config, RequestOptions } from "./types"
|
||||||
import {
|
import {
|
||||||
buildUrl,
|
buildUrl,
|
||||||
createConfig,
|
createConfig,
|
||||||
@@ -7,189 +7,179 @@ import {
|
|||||||
mergeConfigs,
|
mergeConfigs,
|
||||||
mergeHeaders,
|
mergeHeaders,
|
||||||
setAuthParams,
|
setAuthParams,
|
||||||
} from './utils';
|
} from "./utils"
|
||||||
|
|
||||||
type ReqInit = Omit<RequestInit, 'body' | 'headers'> & {
|
type ReqInit = Omit<RequestInit, "body" | "headers"> & {
|
||||||
body?: any;
|
body?: any
|
||||||
headers: ReturnType<typeof mergeHeaders>;
|
headers: ReturnType<typeof mergeHeaders>
|
||||||
};
|
}
|
||||||
|
|
||||||
export const createClient = (config: Config = {}): Client => {
|
export const createClient = (config: Config = {}): Client => {
|
||||||
let _config = mergeConfigs(createConfig(), config);
|
let _config = mergeConfigs(createConfig(), config)
|
||||||
|
|
||||||
const getConfig = (): Config => ({ ..._config });
|
const getConfig = (): Config => ({ ..._config })
|
||||||
|
|
||||||
const setConfig = (config: Config): Config => {
|
const setConfig = (config: Config): Config => {
|
||||||
_config = mergeConfigs(_config, config);
|
_config = mergeConfigs(_config, config)
|
||||||
return getConfig();
|
return getConfig()
|
||||||
};
|
}
|
||||||
|
|
||||||
const interceptors = createInterceptors<
|
const interceptors = createInterceptors<Request, Response, unknown, RequestOptions>()
|
||||||
Request,
|
|
||||||
Response,
|
|
||||||
unknown,
|
|
||||||
RequestOptions
|
|
||||||
>();
|
|
||||||
|
|
||||||
const request: Client['request'] = async (options) => {
|
const request: Client["request"] = async (options) => {
|
||||||
const opts = {
|
const opts = {
|
||||||
..._config,
|
..._config,
|
||||||
...options,
|
...options,
|
||||||
fetch: options.fetch ?? _config.fetch ?? globalThis.fetch,
|
fetch: options.fetch ?? _config.fetch ?? globalThis.fetch,
|
||||||
headers: mergeHeaders(_config.headers, options.headers),
|
headers: mergeHeaders(_config.headers, options.headers),
|
||||||
};
|
}
|
||||||
|
|
||||||
if (opts.security) {
|
if (opts.security) {
|
||||||
await setAuthParams({
|
await setAuthParams({
|
||||||
...opts,
|
...opts,
|
||||||
security: opts.security,
|
security: opts.security,
|
||||||
});
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
if (opts.requestValidator) {
|
if (opts.requestValidator) {
|
||||||
await opts.requestValidator(opts);
|
await opts.requestValidator(opts)
|
||||||
}
|
}
|
||||||
|
|
||||||
if (opts.body && opts.bodySerializer) {
|
if (opts.body && opts.bodySerializer) {
|
||||||
opts.body = opts.bodySerializer(opts.body);
|
opts.body = opts.bodySerializer(opts.body)
|
||||||
}
|
}
|
||||||
|
|
||||||
// remove Content-Type header if body is empty to avoid sending invalid requests
|
// remove Content-Type header if body is empty to avoid sending invalid requests
|
||||||
if (opts.body === undefined || opts.body === '') {
|
if (opts.body === undefined || opts.body === "") {
|
||||||
opts.headers.delete('Content-Type');
|
opts.headers.delete("Content-Type")
|
||||||
}
|
}
|
||||||
|
|
||||||
const url = buildUrl(opts);
|
const url = buildUrl(opts)
|
||||||
const requestInit: ReqInit = {
|
const requestInit: ReqInit = {
|
||||||
redirect: 'follow',
|
redirect: "follow",
|
||||||
...opts,
|
...opts,
|
||||||
};
|
}
|
||||||
|
|
||||||
let request = new Request(url, requestInit);
|
let request = new Request(url, requestInit)
|
||||||
|
|
||||||
for (const fn of interceptors.request._fns) {
|
for (const fn of interceptors.request._fns) {
|
||||||
if (fn) {
|
if (fn) {
|
||||||
request = await fn(request, opts);
|
request = await fn(request, opts)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// fetch must be assigned here, otherwise it would throw the error:
|
// fetch must be assigned here, otherwise it would throw the error:
|
||||||
// TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation
|
// TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation
|
||||||
const _fetch = opts.fetch!;
|
const _fetch = opts.fetch!
|
||||||
let response = await _fetch(request);
|
let response = await _fetch(request)
|
||||||
|
|
||||||
for (const fn of interceptors.response._fns) {
|
for (const fn of interceptors.response._fns) {
|
||||||
if (fn) {
|
if (fn) {
|
||||||
response = await fn(response, request, opts);
|
response = await fn(response, request, opts)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const result = {
|
const result = {
|
||||||
request,
|
request,
|
||||||
response,
|
response,
|
||||||
};
|
}
|
||||||
|
|
||||||
if (response.ok) {
|
if (response.ok) {
|
||||||
if (
|
if (response.status === 204 || response.headers.get("Content-Length") === "0") {
|
||||||
response.status === 204 ||
|
return opts.responseStyle === "data"
|
||||||
response.headers.get('Content-Length') === '0'
|
|
||||||
) {
|
|
||||||
return opts.responseStyle === 'data'
|
|
||||||
? {}
|
? {}
|
||||||
: {
|
: {
|
||||||
data: {},
|
data: {},
|
||||||
...result,
|
...result,
|
||||||
};
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const parseAs =
|
const parseAs =
|
||||||
(opts.parseAs === 'auto'
|
(opts.parseAs === "auto" ? getParseAs(response.headers.get("Content-Type")) : opts.parseAs) ?? "json"
|
||||||
? getParseAs(response.headers.get('Content-Type'))
|
|
||||||
: opts.parseAs) ?? 'json';
|
|
||||||
|
|
||||||
let data: any;
|
let data: any
|
||||||
switch (parseAs) {
|
switch (parseAs) {
|
||||||
case 'arrayBuffer':
|
case "arrayBuffer":
|
||||||
case 'blob':
|
case "blob":
|
||||||
case 'formData':
|
case "formData":
|
||||||
case 'json':
|
case "json":
|
||||||
case 'text':
|
case "text":
|
||||||
data = await response[parseAs]();
|
data = await response[parseAs]()
|
||||||
break;
|
break
|
||||||
case 'stream':
|
case "stream":
|
||||||
return opts.responseStyle === 'data'
|
return opts.responseStyle === "data"
|
||||||
? response.body
|
? response.body
|
||||||
: {
|
: {
|
||||||
data: response.body,
|
data: response.body,
|
||||||
...result,
|
...result,
|
||||||
};
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (parseAs === 'json') {
|
if (parseAs === "json") {
|
||||||
if (opts.responseValidator) {
|
if (opts.responseValidator) {
|
||||||
await opts.responseValidator(data);
|
await opts.responseValidator(data)
|
||||||
}
|
}
|
||||||
|
|
||||||
if (opts.responseTransformer) {
|
if (opts.responseTransformer) {
|
||||||
data = await opts.responseTransformer(data);
|
data = await opts.responseTransformer(data)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return opts.responseStyle === 'data'
|
return opts.responseStyle === "data"
|
||||||
? data
|
? data
|
||||||
: {
|
: {
|
||||||
data,
|
data,
|
||||||
...result,
|
...result,
|
||||||
};
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const textError = await response.text();
|
const textError = await response.text()
|
||||||
let jsonError: unknown;
|
let jsonError: unknown
|
||||||
|
|
||||||
try {
|
try {
|
||||||
jsonError = JSON.parse(textError);
|
jsonError = JSON.parse(textError)
|
||||||
} catch {
|
} catch {
|
||||||
// noop
|
// noop
|
||||||
}
|
}
|
||||||
|
|
||||||
const error = jsonError ?? textError;
|
const error = jsonError ?? textError
|
||||||
let finalError = error;
|
let finalError = error
|
||||||
|
|
||||||
for (const fn of interceptors.error._fns) {
|
for (const fn of interceptors.error._fns) {
|
||||||
if (fn) {
|
if (fn) {
|
||||||
finalError = (await fn(error, response, request, opts)) as string;
|
finalError = (await fn(error, response, request, opts)) as string
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
finalError = finalError || ({} as string);
|
finalError = finalError || ({} as string)
|
||||||
|
|
||||||
if (opts.throwOnError) {
|
if (opts.throwOnError) {
|
||||||
throw finalError;
|
throw finalError
|
||||||
}
|
}
|
||||||
|
|
||||||
// TODO: we probably want to return error and improve types
|
// TODO: we probably want to return error and improve types
|
||||||
return opts.responseStyle === 'data'
|
return opts.responseStyle === "data"
|
||||||
? undefined
|
? undefined
|
||||||
: {
|
: {
|
||||||
error: finalError,
|
error: finalError,
|
||||||
...result,
|
...result,
|
||||||
};
|
}
|
||||||
};
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
buildUrl,
|
buildUrl,
|
||||||
connect: (options) => request({ ...options, method: 'CONNECT' }),
|
connect: (options) => request({ ...options, method: "CONNECT" }),
|
||||||
delete: (options) => request({ ...options, method: 'DELETE' }),
|
delete: (options) => request({ ...options, method: "DELETE" }),
|
||||||
get: (options) => request({ ...options, method: 'GET' }),
|
get: (options) => request({ ...options, method: "GET" }),
|
||||||
getConfig,
|
getConfig,
|
||||||
head: (options) => request({ ...options, method: 'HEAD' }),
|
head: (options) => request({ ...options, method: "HEAD" }),
|
||||||
interceptors,
|
interceptors,
|
||||||
options: (options) => request({ ...options, method: 'OPTIONS' }),
|
options: (options) => request({ ...options, method: "OPTIONS" }),
|
||||||
patch: (options) => request({ ...options, method: 'PATCH' }),
|
patch: (options) => request({ ...options, method: "PATCH" }),
|
||||||
post: (options) => request({ ...options, method: 'POST' }),
|
post: (options) => request({ ...options, method: "POST" }),
|
||||||
put: (options) => request({ ...options, method: 'PUT' }),
|
put: (options) => request({ ...options, method: "PUT" }),
|
||||||
request,
|
request,
|
||||||
setConfig,
|
setConfig,
|
||||||
trace: (options) => request({ ...options, method: 'TRACE' }),
|
trace: (options) => request({ ...options, method: "TRACE" }),
|
||||||
};
|
}
|
||||||
};
|
}
|
||||||
|
|||||||
@@ -1,12 +1,8 @@
|
|||||||
export type { Auth } from '../core/auth';
|
export type { Auth } from "../core/auth"
|
||||||
export type { QuerySerializerOptions } from '../core/bodySerializer';
|
export type { QuerySerializerOptions } from "../core/bodySerializer"
|
||||||
export {
|
export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer } from "../core/bodySerializer"
|
||||||
formDataBodySerializer,
|
export { buildClientParams } from "../core/params"
|
||||||
jsonBodySerializer,
|
export { createClient } from "./client"
|
||||||
urlSearchParamsBodySerializer,
|
|
||||||
} from '../core/bodySerializer';
|
|
||||||
export { buildClientParams } from '../core/params';
|
|
||||||
export { createClient } from './client';
|
|
||||||
export type {
|
export type {
|
||||||
Client,
|
Client,
|
||||||
ClientOptions,
|
ClientOptions,
|
||||||
@@ -18,5 +14,5 @@ export type {
|
|||||||
RequestResult,
|
RequestResult,
|
||||||
ResponseStyle,
|
ResponseStyle,
|
||||||
TDataShape,
|
TDataShape,
|
||||||
} from './types';
|
} from "./types"
|
||||||
export { createConfig, mergeHeaders } from './utils';
|
export { createConfig, mergeHeaders } from "./utils"
|
||||||
|
|||||||
@@ -1,33 +1,30 @@
|
|||||||
import type { Auth } from '../core/auth';
|
import type { Auth } from "../core/auth"
|
||||||
import type {
|
import type { Client as CoreClient, Config as CoreConfig } from "../core/types"
|
||||||
Client as CoreClient,
|
import type { Middleware } from "./utils"
|
||||||
Config as CoreConfig,
|
|
||||||
} from '../core/types';
|
|
||||||
import type { Middleware } from './utils';
|
|
||||||
|
|
||||||
export type ResponseStyle = 'data' | 'fields';
|
export type ResponseStyle = "data" | "fields"
|
||||||
|
|
||||||
export interface Config<T extends ClientOptions = ClientOptions>
|
export interface Config<T extends ClientOptions = ClientOptions>
|
||||||
extends Omit<RequestInit, 'body' | 'headers' | 'method'>,
|
extends Omit<RequestInit, "body" | "headers" | "method">,
|
||||||
CoreConfig {
|
CoreConfig {
|
||||||
/**
|
/**
|
||||||
* Base URL for all requests made by this client.
|
* Base URL for all requests made by this client.
|
||||||
*/
|
*/
|
||||||
baseUrl?: T['baseUrl'];
|
baseUrl?: T["baseUrl"]
|
||||||
/**
|
/**
|
||||||
* Fetch API implementation. You can use this option to provide a custom
|
* Fetch API implementation. You can use this option to provide a custom
|
||||||
* fetch instance.
|
* fetch instance.
|
||||||
*
|
*
|
||||||
* @default globalThis.fetch
|
* @default globalThis.fetch
|
||||||
*/
|
*/
|
||||||
fetch?: (request: Request) => ReturnType<typeof fetch>;
|
fetch?: (request: Request) => ReturnType<typeof fetch>
|
||||||
/**
|
/**
|
||||||
* Please don't use the Fetch client for Next.js applications. The `next`
|
* Please don't use the Fetch client for Next.js applications. The `next`
|
||||||
* options won't have any effect.
|
* options won't have any effect.
|
||||||
*
|
*
|
||||||
* Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead.
|
* Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead.
|
||||||
*/
|
*/
|
||||||
next?: never;
|
next?: never
|
||||||
/**
|
/**
|
||||||
* Return the response data parsed in a specified format. By default, `auto`
|
* Return the response data parsed in a specified format. By default, `auto`
|
||||||
* will infer the appropriate method from the `Content-Type` response header.
|
* will infer the appropriate method from the `Content-Type` response header.
|
||||||
@@ -36,135 +33,118 @@ export interface Config<T extends ClientOptions = ClientOptions>
|
|||||||
*
|
*
|
||||||
* @default 'auto'
|
* @default 'auto'
|
||||||
*/
|
*/
|
||||||
parseAs?:
|
parseAs?: "arrayBuffer" | "auto" | "blob" | "formData" | "json" | "stream" | "text"
|
||||||
| 'arrayBuffer'
|
|
||||||
| 'auto'
|
|
||||||
| 'blob'
|
|
||||||
| 'formData'
|
|
||||||
| 'json'
|
|
||||||
| 'stream'
|
|
||||||
| 'text';
|
|
||||||
/**
|
/**
|
||||||
* Should we return only data or multiple fields (data, error, response, etc.)?
|
* Should we return only data or multiple fields (data, error, response, etc.)?
|
||||||
*
|
*
|
||||||
* @default 'fields'
|
* @default 'fields'
|
||||||
*/
|
*/
|
||||||
responseStyle?: ResponseStyle;
|
responseStyle?: ResponseStyle
|
||||||
/**
|
/**
|
||||||
* Throw an error instead of returning it in the response?
|
* Throw an error instead of returning it in the response?
|
||||||
*
|
*
|
||||||
* @default false
|
* @default false
|
||||||
*/
|
*/
|
||||||
throwOnError?: T['throwOnError'];
|
throwOnError?: T["throwOnError"]
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface RequestOptions<
|
export interface RequestOptions<
|
||||||
TResponseStyle extends ResponseStyle = 'fields',
|
TResponseStyle extends ResponseStyle = "fields",
|
||||||
ThrowOnError extends boolean = boolean,
|
ThrowOnError extends boolean = boolean,
|
||||||
Url extends string = string,
|
Url extends string = string,
|
||||||
> extends Config<{
|
> extends Config<{
|
||||||
responseStyle: TResponseStyle;
|
responseStyle: TResponseStyle
|
||||||
throwOnError: ThrowOnError;
|
throwOnError: ThrowOnError
|
||||||
}> {
|
}> {
|
||||||
/**
|
/**
|
||||||
* Any body that you want to add to your request.
|
* Any body that you want to add to your request.
|
||||||
*
|
*
|
||||||
* {@link https://developer.mozilla.org/docs/Web/API/fetch#body}
|
* {@link https://developer.mozilla.org/docs/Web/API/fetch#body}
|
||||||
*/
|
*/
|
||||||
body?: unknown;
|
body?: unknown
|
||||||
path?: Record<string, unknown>;
|
path?: Record<string, unknown>
|
||||||
query?: Record<string, unknown>;
|
query?: Record<string, unknown>
|
||||||
/**
|
/**
|
||||||
* Security mechanism(s) to use for the request.
|
* Security mechanism(s) to use for the request.
|
||||||
*/
|
*/
|
||||||
security?: ReadonlyArray<Auth>;
|
security?: ReadonlyArray<Auth>
|
||||||
url: Url;
|
url: Url
|
||||||
}
|
}
|
||||||
|
|
||||||
export type RequestResult<
|
export type RequestResult<
|
||||||
TData = unknown,
|
TData = unknown,
|
||||||
TError = unknown,
|
TError = unknown,
|
||||||
ThrowOnError extends boolean = boolean,
|
ThrowOnError extends boolean = boolean,
|
||||||
TResponseStyle extends ResponseStyle = 'fields',
|
TResponseStyle extends ResponseStyle = "fields",
|
||||||
> = ThrowOnError extends true
|
> = ThrowOnError extends true
|
||||||
? Promise<
|
? Promise<
|
||||||
TResponseStyle extends 'data'
|
TResponseStyle extends "data"
|
||||||
? TData extends Record<string, unknown>
|
? TData extends Record<string, unknown>
|
||||||
? TData[keyof TData]
|
? TData[keyof TData]
|
||||||
: TData
|
: TData
|
||||||
: {
|
: {
|
||||||
data: TData extends Record<string, unknown>
|
data: TData extends Record<string, unknown> ? TData[keyof TData] : TData
|
||||||
? TData[keyof TData]
|
request: Request
|
||||||
: TData;
|
response: Response
|
||||||
request: Request;
|
|
||||||
response: Response;
|
|
||||||
}
|
}
|
||||||
>
|
>
|
||||||
: Promise<
|
: Promise<
|
||||||
TResponseStyle extends 'data'
|
TResponseStyle extends "data"
|
||||||
?
|
? (TData extends Record<string, unknown> ? TData[keyof TData] : TData) | undefined
|
||||||
| (TData extends Record<string, unknown>
|
|
||||||
? TData[keyof TData]
|
|
||||||
: TData)
|
|
||||||
| undefined
|
|
||||||
: (
|
: (
|
||||||
| {
|
| {
|
||||||
data: TData extends Record<string, unknown>
|
data: TData extends Record<string, unknown> ? TData[keyof TData] : TData
|
||||||
? TData[keyof TData]
|
error: undefined
|
||||||
: TData;
|
|
||||||
error: undefined;
|
|
||||||
}
|
}
|
||||||
| {
|
| {
|
||||||
data: undefined;
|
data: undefined
|
||||||
error: TError extends Record<string, unknown>
|
error: TError extends Record<string, unknown> ? TError[keyof TError] : TError
|
||||||
? TError[keyof TError]
|
|
||||||
: TError;
|
|
||||||
}
|
}
|
||||||
) & {
|
) & {
|
||||||
request: Request;
|
request: Request
|
||||||
response: Response;
|
response: Response
|
||||||
}
|
}
|
||||||
>;
|
>
|
||||||
|
|
||||||
export interface ClientOptions {
|
export interface ClientOptions {
|
||||||
baseUrl?: string;
|
baseUrl?: string
|
||||||
responseStyle?: ResponseStyle;
|
responseStyle?: ResponseStyle
|
||||||
throwOnError?: boolean;
|
throwOnError?: boolean
|
||||||
}
|
}
|
||||||
|
|
||||||
type MethodFn = <
|
type MethodFn = <
|
||||||
TData = unknown,
|
TData = unknown,
|
||||||
TError = unknown,
|
TError = unknown,
|
||||||
ThrowOnError extends boolean = false,
|
ThrowOnError extends boolean = false,
|
||||||
TResponseStyle extends ResponseStyle = 'fields',
|
TResponseStyle extends ResponseStyle = "fields",
|
||||||
>(
|
>(
|
||||||
options: Omit<RequestOptions<TResponseStyle, ThrowOnError>, 'method'>,
|
options: Omit<RequestOptions<TResponseStyle, ThrowOnError>, "method">,
|
||||||
) => RequestResult<TData, TError, ThrowOnError, TResponseStyle>;
|
) => RequestResult<TData, TError, ThrowOnError, TResponseStyle>
|
||||||
|
|
||||||
type RequestFn = <
|
type RequestFn = <
|
||||||
TData = unknown,
|
TData = unknown,
|
||||||
TError = unknown,
|
TError = unknown,
|
||||||
ThrowOnError extends boolean = false,
|
ThrowOnError extends boolean = false,
|
||||||
TResponseStyle extends ResponseStyle = 'fields',
|
TResponseStyle extends ResponseStyle = "fields",
|
||||||
>(
|
>(
|
||||||
options: Omit<RequestOptions<TResponseStyle, ThrowOnError>, 'method'> &
|
options: Omit<RequestOptions<TResponseStyle, ThrowOnError>, "method"> &
|
||||||
Pick<Required<RequestOptions<TResponseStyle, ThrowOnError>>, 'method'>,
|
Pick<Required<RequestOptions<TResponseStyle, ThrowOnError>>, "method">,
|
||||||
) => RequestResult<TData, TError, ThrowOnError, TResponseStyle>;
|
) => RequestResult<TData, TError, ThrowOnError, TResponseStyle>
|
||||||
|
|
||||||
type BuildUrlFn = <
|
type BuildUrlFn = <
|
||||||
TData extends {
|
TData extends {
|
||||||
body?: unknown;
|
body?: unknown
|
||||||
path?: Record<string, unknown>;
|
path?: Record<string, unknown>
|
||||||
query?: Record<string, unknown>;
|
query?: Record<string, unknown>
|
||||||
url: string;
|
url: string
|
||||||
},
|
},
|
||||||
>(
|
>(
|
||||||
options: Pick<TData, 'url'> & Options<TData>,
|
options: Pick<TData, "url"> & Options<TData>,
|
||||||
) => string;
|
) => string
|
||||||
|
|
||||||
export type Client = CoreClient<RequestFn, Config, MethodFn, BuildUrlFn> & {
|
export type Client = CoreClient<RequestFn, Config, MethodFn, BuildUrlFn> & {
|
||||||
interceptors: Middleware<Request, Response, unknown, RequestOptions>;
|
interceptors: Middleware<Request, Response, unknown, RequestOptions>
|
||||||
};
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The `createClientConfig()` function will be called on client initialization
|
* The `createClientConfig()` function will be called on client initialization
|
||||||
@@ -176,47 +156,36 @@ export type Client = CoreClient<RequestFn, Config, MethodFn, BuildUrlFn> & {
|
|||||||
*/
|
*/
|
||||||
export type CreateClientConfig<T extends ClientOptions = ClientOptions> = (
|
export type CreateClientConfig<T extends ClientOptions = ClientOptions> = (
|
||||||
override?: Config<ClientOptions & T>,
|
override?: Config<ClientOptions & T>,
|
||||||
) => Config<Required<ClientOptions> & T>;
|
) => Config<Required<ClientOptions> & T>
|
||||||
|
|
||||||
export interface TDataShape {
|
export interface TDataShape {
|
||||||
body?: unknown;
|
body?: unknown
|
||||||
headers?: unknown;
|
headers?: unknown
|
||||||
path?: unknown;
|
path?: unknown
|
||||||
query?: unknown;
|
query?: unknown
|
||||||
url: string;
|
url: string
|
||||||
}
|
}
|
||||||
|
|
||||||
type OmitKeys<T, K> = Pick<T, Exclude<keyof T, K>>;
|
type OmitKeys<T, K> = Pick<T, Exclude<keyof T, K>>
|
||||||
|
|
||||||
export type Options<
|
export type Options<
|
||||||
TData extends TDataShape = TDataShape,
|
TData extends TDataShape = TDataShape,
|
||||||
ThrowOnError extends boolean = boolean,
|
ThrowOnError extends boolean = boolean,
|
||||||
TResponseStyle extends ResponseStyle = 'fields',
|
TResponseStyle extends ResponseStyle = "fields",
|
||||||
> = OmitKeys<
|
> = OmitKeys<RequestOptions<TResponseStyle, ThrowOnError>, "body" | "path" | "query" | "url"> & Omit<TData, "url">
|
||||||
RequestOptions<TResponseStyle, ThrowOnError>,
|
|
||||||
'body' | 'path' | 'query' | 'url'
|
|
||||||
> &
|
|
||||||
Omit<TData, 'url'>;
|
|
||||||
|
|
||||||
export type OptionsLegacyParser<
|
export type OptionsLegacyParser<
|
||||||
TData = unknown,
|
TData = unknown,
|
||||||
ThrowOnError extends boolean = boolean,
|
ThrowOnError extends boolean = boolean,
|
||||||
TResponseStyle extends ResponseStyle = 'fields',
|
TResponseStyle extends ResponseStyle = "fields",
|
||||||
> = TData extends { body?: any }
|
> = TData extends { body?: any }
|
||||||
? TData extends { headers?: any }
|
? TData extends { headers?: any }
|
||||||
? OmitKeys<
|
? OmitKeys<RequestOptions<TResponseStyle, ThrowOnError>, "body" | "headers" | "url"> & TData
|
||||||
RequestOptions<TResponseStyle, ThrowOnError>,
|
: OmitKeys<RequestOptions<TResponseStyle, ThrowOnError>, "body" | "url"> &
|
||||||
'body' | 'headers' | 'url'
|
|
||||||
> &
|
|
||||||
TData
|
|
||||||
: OmitKeys<RequestOptions<TResponseStyle, ThrowOnError>, 'body' | 'url'> &
|
|
||||||
TData &
|
TData &
|
||||||
Pick<RequestOptions<TResponseStyle, ThrowOnError>, 'headers'>
|
Pick<RequestOptions<TResponseStyle, ThrowOnError>, "headers">
|
||||||
: TData extends { headers?: any }
|
: TData extends { headers?: any }
|
||||||
? OmitKeys<
|
? OmitKeys<RequestOptions<TResponseStyle, ThrowOnError>, "headers" | "url"> &
|
||||||
RequestOptions<TResponseStyle, ThrowOnError>,
|
|
||||||
'headers' | 'url'
|
|
||||||
> &
|
|
||||||
TData &
|
TData &
|
||||||
Pick<RequestOptions<TResponseStyle, ThrowOnError>, 'body'>
|
Pick<RequestOptions<TResponseStyle, ThrowOnError>, "body">
|
||||||
: OmitKeys<RequestOptions<TResponseStyle, ThrowOnError>, 'url'> & TData;
|
: OmitKeys<RequestOptions<TResponseStyle, ThrowOnError>, "url"> & TData
|
||||||
|
|||||||
@@ -1,64 +1,54 @@
|
|||||||
import { getAuthToken } from '../core/auth';
|
import { getAuthToken } from "../core/auth"
|
||||||
import type {
|
import type { QuerySerializer, QuerySerializerOptions } from "../core/bodySerializer"
|
||||||
QuerySerializer,
|
import { jsonBodySerializer } from "../core/bodySerializer"
|
||||||
QuerySerializerOptions,
|
import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam } from "../core/pathSerializer"
|
||||||
} from '../core/bodySerializer';
|
import type { Client, ClientOptions, Config, RequestOptions } from "./types"
|
||||||
import { jsonBodySerializer } from '../core/bodySerializer';
|
|
||||||
import {
|
|
||||||
serializeArrayParam,
|
|
||||||
serializeObjectParam,
|
|
||||||
serializePrimitiveParam,
|
|
||||||
} from '../core/pathSerializer';
|
|
||||||
import type { Client, ClientOptions, Config, RequestOptions } from './types';
|
|
||||||
|
|
||||||
interface PathSerializer {
|
interface PathSerializer {
|
||||||
path: Record<string, unknown>;
|
path: Record<string, unknown>
|
||||||
url: string;
|
url: string
|
||||||
}
|
}
|
||||||
|
|
||||||
const PATH_PARAM_RE = /\{[^{}]+\}/g;
|
const PATH_PARAM_RE = /\{[^{}]+\}/g
|
||||||
|
|
||||||
type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited';
|
type ArrayStyle = "form" | "spaceDelimited" | "pipeDelimited"
|
||||||
type MatrixStyle = 'label' | 'matrix' | 'simple';
|
type MatrixStyle = "label" | "matrix" | "simple"
|
||||||
type ArraySeparatorStyle = ArrayStyle | MatrixStyle;
|
type ArraySeparatorStyle = ArrayStyle | MatrixStyle
|
||||||
|
|
||||||
const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => {
|
const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => {
|
||||||
let url = _url;
|
let url = _url
|
||||||
const matches = _url.match(PATH_PARAM_RE);
|
const matches = _url.match(PATH_PARAM_RE)
|
||||||
if (matches) {
|
if (matches) {
|
||||||
for (const match of matches) {
|
for (const match of matches) {
|
||||||
let explode = false;
|
let explode = false
|
||||||
let name = match.substring(1, match.length - 1);
|
let name = match.substring(1, match.length - 1)
|
||||||
let style: ArraySeparatorStyle = 'simple';
|
let style: ArraySeparatorStyle = "simple"
|
||||||
|
|
||||||
if (name.endsWith('*')) {
|
if (name.endsWith("*")) {
|
||||||
explode = true;
|
explode = true
|
||||||
name = name.substring(0, name.length - 1);
|
name = name.substring(0, name.length - 1)
|
||||||
}
|
}
|
||||||
|
|
||||||
if (name.startsWith('.')) {
|
if (name.startsWith(".")) {
|
||||||
name = name.substring(1);
|
name = name.substring(1)
|
||||||
style = 'label';
|
style = "label"
|
||||||
} else if (name.startsWith(';')) {
|
} else if (name.startsWith(";")) {
|
||||||
name = name.substring(1);
|
name = name.substring(1)
|
||||||
style = 'matrix';
|
style = "matrix"
|
||||||
}
|
}
|
||||||
|
|
||||||
const value = path[name];
|
const value = path[name]
|
||||||
|
|
||||||
if (value === undefined || value === null) {
|
if (value === undefined || value === null) {
|
||||||
continue;
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
if (Array.isArray(value)) {
|
if (Array.isArray(value)) {
|
||||||
url = url.replace(
|
url = url.replace(match, serializeArrayParam({ explode, name, style, value }))
|
||||||
match,
|
continue
|
||||||
serializeArrayParam({ explode, name, style, value }),
|
|
||||||
);
|
|
||||||
continue;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (typeof value === 'object') {
|
if (typeof value === "object") {
|
||||||
url = url.replace(
|
url = url.replace(
|
||||||
match,
|
match,
|
||||||
serializeObjectParam({
|
serializeObjectParam({
|
||||||
@@ -68,43 +58,37 @@ const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => {
|
|||||||
value: value as Record<string, unknown>,
|
value: value as Record<string, unknown>,
|
||||||
valueOnly: true,
|
valueOnly: true,
|
||||||
}),
|
}),
|
||||||
);
|
)
|
||||||
continue;
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
if (style === 'matrix') {
|
if (style === "matrix") {
|
||||||
url = url.replace(
|
url = url.replace(
|
||||||
match,
|
match,
|
||||||
`;${serializePrimitiveParam({
|
`;${serializePrimitiveParam({
|
||||||
name,
|
name,
|
||||||
value: value as string,
|
value: value as string,
|
||||||
})}`,
|
})}`,
|
||||||
);
|
)
|
||||||
continue;
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
const replaceValue = encodeURIComponent(
|
const replaceValue = encodeURIComponent(style === "label" ? `.${value as string}` : (value as string))
|
||||||
style === 'label' ? `.${value as string}` : (value as string),
|
url = url.replace(match, replaceValue)
|
||||||
);
|
|
||||||
url = url.replace(match, replaceValue);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return url;
|
return url
|
||||||
};
|
}
|
||||||
|
|
||||||
export const createQuerySerializer = <T = unknown>({
|
export const createQuerySerializer = <T = unknown>({ allowReserved, array, object }: QuerySerializerOptions = {}) => {
|
||||||
allowReserved,
|
|
||||||
array,
|
|
||||||
object,
|
|
||||||
}: QuerySerializerOptions = {}) => {
|
|
||||||
const querySerializer = (queryParams: T) => {
|
const querySerializer = (queryParams: T) => {
|
||||||
const search: string[] = [];
|
const search: string[] = []
|
||||||
if (queryParams && typeof queryParams === 'object') {
|
if (queryParams && typeof queryParams === "object") {
|
||||||
for (const name in queryParams) {
|
for (const name in queryParams) {
|
||||||
const value = queryParams[name];
|
const value = queryParams[name]
|
||||||
|
|
||||||
if (value === undefined || value === null) {
|
if (value === undefined || value === null) {
|
||||||
continue;
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
if (Array.isArray(value)) {
|
if (Array.isArray(value)) {
|
||||||
@@ -112,129 +96,120 @@ export const createQuerySerializer = <T = unknown>({
|
|||||||
allowReserved,
|
allowReserved,
|
||||||
explode: true,
|
explode: true,
|
||||||
name,
|
name,
|
||||||
style: 'form',
|
style: "form",
|
||||||
value,
|
value,
|
||||||
...array,
|
...array,
|
||||||
});
|
})
|
||||||
if (serializedArray) search.push(serializedArray);
|
if (serializedArray) search.push(serializedArray)
|
||||||
} else if (typeof value === 'object') {
|
} else if (typeof value === "object") {
|
||||||
const serializedObject = serializeObjectParam({
|
const serializedObject = serializeObjectParam({
|
||||||
allowReserved,
|
allowReserved,
|
||||||
explode: true,
|
explode: true,
|
||||||
name,
|
name,
|
||||||
style: 'deepObject',
|
style: "deepObject",
|
||||||
value: value as Record<string, unknown>,
|
value: value as Record<string, unknown>,
|
||||||
...object,
|
...object,
|
||||||
});
|
})
|
||||||
if (serializedObject) search.push(serializedObject);
|
if (serializedObject) search.push(serializedObject)
|
||||||
} else {
|
} else {
|
||||||
const serializedPrimitive = serializePrimitiveParam({
|
const serializedPrimitive = serializePrimitiveParam({
|
||||||
allowReserved,
|
allowReserved,
|
||||||
name,
|
name,
|
||||||
value: value as string,
|
value: value as string,
|
||||||
});
|
})
|
||||||
if (serializedPrimitive) search.push(serializedPrimitive);
|
if (serializedPrimitive) search.push(serializedPrimitive)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return search.join('&');
|
return search.join("&")
|
||||||
};
|
}
|
||||||
return querySerializer;
|
return querySerializer
|
||||||
};
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Infers parseAs value from provided Content-Type header.
|
* Infers parseAs value from provided Content-Type header.
|
||||||
*/
|
*/
|
||||||
export const getParseAs = (
|
export const getParseAs = (contentType: string | null): Exclude<Config["parseAs"], "auto"> => {
|
||||||
contentType: string | null,
|
|
||||||
): Exclude<Config['parseAs'], 'auto'> => {
|
|
||||||
if (!contentType) {
|
if (!contentType) {
|
||||||
// If no Content-Type header is provided, the best we can do is return the raw response body,
|
// 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.
|
// which is effectively the same as the 'stream' option.
|
||||||
return 'stream';
|
return "stream"
|
||||||
}
|
}
|
||||||
|
|
||||||
const cleanContent = contentType.split(';')[0]?.trim();
|
const cleanContent = contentType.split(";")[0]?.trim()
|
||||||
|
|
||||||
if (!cleanContent) {
|
if (!cleanContent) {
|
||||||
return;
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
if (
|
if (cleanContent.startsWith("application/json") || cleanContent.endsWith("+json")) {
|
||||||
cleanContent.startsWith('application/json') ||
|
return "json"
|
||||||
cleanContent.endsWith('+json')
|
|
||||||
) {
|
|
||||||
return 'json';
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (cleanContent === 'multipart/form-data') {
|
if (cleanContent === "multipart/form-data") {
|
||||||
return 'formData';
|
return "formData"
|
||||||
}
|
}
|
||||||
|
|
||||||
if (
|
if (["application/", "audio/", "image/", "video/"].some((type) => cleanContent.startsWith(type))) {
|
||||||
['application/', 'audio/', 'image/', 'video/'].some((type) =>
|
return "blob"
|
||||||
cleanContent.startsWith(type),
|
|
||||||
)
|
|
||||||
) {
|
|
||||||
return 'blob';
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (cleanContent.startsWith('text/')) {
|
if (cleanContent.startsWith("text/")) {
|
||||||
return 'text';
|
return "text"
|
||||||
}
|
}
|
||||||
|
|
||||||
return;
|
return
|
||||||
};
|
}
|
||||||
|
|
||||||
export const setAuthParams = async ({
|
export const setAuthParams = async ({
|
||||||
security,
|
security,
|
||||||
...options
|
...options
|
||||||
}: Pick<Required<RequestOptions>, 'security'> &
|
}: Pick<Required<RequestOptions>, "security"> &
|
||||||
Pick<RequestOptions, 'auth' | 'query'> & {
|
Pick<RequestOptions, "auth" | "query"> & {
|
||||||
headers: Headers;
|
headers: Headers
|
||||||
}) => {
|
}) => {
|
||||||
for (const auth of security) {
|
for (const auth of security) {
|
||||||
const token = await getAuthToken(auth, options.auth);
|
const token = await getAuthToken(auth, options.auth)
|
||||||
|
|
||||||
if (!token) {
|
if (!token) {
|
||||||
continue;
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
const name = auth.name ?? 'Authorization';
|
const name = auth.name ?? "Authorization"
|
||||||
|
|
||||||
switch (auth.in) {
|
switch (auth.in) {
|
||||||
case 'query':
|
case "query":
|
||||||
if (!options.query) {
|
if (!options.query) {
|
||||||
options.query = {};
|
options.query = {}
|
||||||
}
|
}
|
||||||
options.query[name] = token;
|
options.query[name] = token
|
||||||
break;
|
break
|
||||||
case 'cookie':
|
case "cookie":
|
||||||
options.headers.append('Cookie', `${name}=${token}`);
|
options.headers.append("Cookie", `${name}=${token}`)
|
||||||
break;
|
break
|
||||||
case 'header':
|
case "header":
|
||||||
default:
|
default:
|
||||||
options.headers.set(name, token);
|
options.headers.set(name, token)
|
||||||
break;
|
break
|
||||||
}
|
}
|
||||||
|
|
||||||
return;
|
return
|
||||||
}
|
}
|
||||||
};
|
}
|
||||||
|
|
||||||
export const buildUrl: Client['buildUrl'] = (options) => {
|
export const buildUrl: Client["buildUrl"] = (options) => {
|
||||||
const url = getUrl({
|
const url = getUrl({
|
||||||
baseUrl: options.baseUrl as string,
|
baseUrl: options.baseUrl as string,
|
||||||
path: options.path,
|
path: options.path,
|
||||||
query: options.query,
|
query: options.query,
|
||||||
querySerializer:
|
querySerializer:
|
||||||
typeof options.querySerializer === 'function'
|
typeof options.querySerializer === "function"
|
||||||
? options.querySerializer
|
? options.querySerializer
|
||||||
: createQuerySerializer(options.querySerializer),
|
: createQuerySerializer(options.querySerializer),
|
||||||
url: options.url,
|
url: options.url,
|
||||||
});
|
})
|
||||||
return url;
|
return url
|
||||||
};
|
}
|
||||||
|
|
||||||
export const getUrl = ({
|
export const getUrl = ({
|
||||||
baseUrl,
|
baseUrl,
|
||||||
@@ -243,144 +218,125 @@ export const getUrl = ({
|
|||||||
querySerializer,
|
querySerializer,
|
||||||
url: _url,
|
url: _url,
|
||||||
}: {
|
}: {
|
||||||
baseUrl?: string;
|
baseUrl?: string
|
||||||
path?: Record<string, unknown>;
|
path?: Record<string, unknown>
|
||||||
query?: Record<string, unknown>;
|
query?: Record<string, unknown>
|
||||||
querySerializer: QuerySerializer;
|
querySerializer: QuerySerializer
|
||||||
url: string;
|
url: string
|
||||||
}) => {
|
}) => {
|
||||||
const pathUrl = _url.startsWith('/') ? _url : `/${_url}`;
|
const pathUrl = _url.startsWith("/") ? _url : `/${_url}`
|
||||||
let url = (baseUrl ?? '') + pathUrl;
|
let url = (baseUrl ?? "") + pathUrl
|
||||||
if (path) {
|
if (path) {
|
||||||
url = defaultPathSerializer({ path, url });
|
url = defaultPathSerializer({ path, url })
|
||||||
}
|
}
|
||||||
let search = query ? querySerializer(query) : '';
|
let search = query ? querySerializer(query) : ""
|
||||||
if (search.startsWith('?')) {
|
if (search.startsWith("?")) {
|
||||||
search = search.substring(1);
|
search = search.substring(1)
|
||||||
}
|
}
|
||||||
if (search) {
|
if (search) {
|
||||||
url += `?${search}`;
|
url += `?${search}`
|
||||||
}
|
}
|
||||||
return url;
|
return url
|
||||||
};
|
}
|
||||||
|
|
||||||
export const mergeConfigs = (a: Config, b: Config): Config => {
|
export const mergeConfigs = (a: Config, b: Config): Config => {
|
||||||
const config = { ...a, ...b };
|
const config = { ...a, ...b }
|
||||||
if (config.baseUrl?.endsWith('/')) {
|
if (config.baseUrl?.endsWith("/")) {
|
||||||
config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1);
|
config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1)
|
||||||
}
|
}
|
||||||
config.headers = mergeHeaders(a.headers, b.headers);
|
config.headers = mergeHeaders(a.headers, b.headers)
|
||||||
return config;
|
return config
|
||||||
};
|
}
|
||||||
|
|
||||||
export const mergeHeaders = (
|
export const mergeHeaders = (...headers: Array<Required<Config>["headers"] | undefined>): Headers => {
|
||||||
...headers: Array<Required<Config>['headers'] | undefined>
|
const mergedHeaders = new Headers()
|
||||||
): Headers => {
|
|
||||||
const mergedHeaders = new Headers();
|
|
||||||
for (const header of headers) {
|
for (const header of headers) {
|
||||||
if (!header || typeof header !== 'object') {
|
if (!header || typeof header !== "object") {
|
||||||
continue;
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
const iterator =
|
const iterator = header instanceof Headers ? header.entries() : Object.entries(header)
|
||||||
header instanceof Headers ? header.entries() : Object.entries(header);
|
|
||||||
|
|
||||||
for (const [key, value] of iterator) {
|
for (const [key, value] of iterator) {
|
||||||
if (value === null) {
|
if (value === null) {
|
||||||
mergedHeaders.delete(key);
|
mergedHeaders.delete(key)
|
||||||
} else if (Array.isArray(value)) {
|
} else if (Array.isArray(value)) {
|
||||||
for (const v of value) {
|
for (const v of value) {
|
||||||
mergedHeaders.append(key, v as string);
|
mergedHeaders.append(key, v as string)
|
||||||
}
|
}
|
||||||
} else if (value !== undefined) {
|
} else if (value !== undefined) {
|
||||||
// assume object headers are meant to be JSON stringified, i.e. their
|
// assume object headers are meant to be JSON stringified, i.e. their
|
||||||
// content value in OpenAPI specification is 'application/json'
|
// content value in OpenAPI specification is 'application/json'
|
||||||
mergedHeaders.set(
|
mergedHeaders.set(key, typeof value === "object" ? JSON.stringify(value) : (value as string))
|
||||||
key,
|
|
||||||
typeof value === 'object' ? JSON.stringify(value) : (value as string),
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return mergedHeaders;
|
return mergedHeaders
|
||||||
};
|
}
|
||||||
|
|
||||||
type ErrInterceptor<Err, Res, Req, Options> = (
|
type ErrInterceptor<Err, Res, Req, Options> = (
|
||||||
error: Err,
|
error: Err,
|
||||||
response: Res,
|
response: Res,
|
||||||
request: Req,
|
request: Req,
|
||||||
options: Options,
|
options: Options,
|
||||||
) => Err | Promise<Err>;
|
) => Err | Promise<Err>
|
||||||
|
|
||||||
type ReqInterceptor<Req, Options> = (
|
type ReqInterceptor<Req, Options> = (request: Req, options: Options) => Req | Promise<Req>
|
||||||
request: Req,
|
|
||||||
options: Options,
|
|
||||||
) => Req | Promise<Req>;
|
|
||||||
|
|
||||||
type ResInterceptor<Res, Req, Options> = (
|
type ResInterceptor<Res, Req, Options> = (response: Res, request: Req, options: Options) => Res | Promise<Res>
|
||||||
response: Res,
|
|
||||||
request: Req,
|
|
||||||
options: Options,
|
|
||||||
) => Res | Promise<Res>;
|
|
||||||
|
|
||||||
class Interceptors<Interceptor> {
|
class Interceptors<Interceptor> {
|
||||||
_fns: (Interceptor | null)[];
|
_fns: (Interceptor | null)[]
|
||||||
|
|
||||||
constructor() {
|
constructor() {
|
||||||
this._fns = [];
|
this._fns = []
|
||||||
}
|
}
|
||||||
|
|
||||||
clear() {
|
clear() {
|
||||||
this._fns = [];
|
this._fns = []
|
||||||
}
|
}
|
||||||
|
|
||||||
getInterceptorIndex(id: number | Interceptor): number {
|
getInterceptorIndex(id: number | Interceptor): number {
|
||||||
if (typeof id === 'number') {
|
if (typeof id === "number") {
|
||||||
return this._fns[id] ? id : -1;
|
return this._fns[id] ? id : -1
|
||||||
} else {
|
} else {
|
||||||
return this._fns.indexOf(id);
|
return this._fns.indexOf(id)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
exists(id: number | Interceptor) {
|
exists(id: number | Interceptor) {
|
||||||
const index = this.getInterceptorIndex(id);
|
const index = this.getInterceptorIndex(id)
|
||||||
return !!this._fns[index];
|
return !!this._fns[index]
|
||||||
}
|
}
|
||||||
|
|
||||||
eject(id: number | Interceptor) {
|
eject(id: number | Interceptor) {
|
||||||
const index = this.getInterceptorIndex(id);
|
const index = this.getInterceptorIndex(id)
|
||||||
if (this._fns[index]) {
|
if (this._fns[index]) {
|
||||||
this._fns[index] = null;
|
this._fns[index] = null
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
update(id: number | Interceptor, fn: Interceptor) {
|
update(id: number | Interceptor, fn: Interceptor) {
|
||||||
const index = this.getInterceptorIndex(id);
|
const index = this.getInterceptorIndex(id)
|
||||||
if (this._fns[index]) {
|
if (this._fns[index]) {
|
||||||
this._fns[index] = fn;
|
this._fns[index] = fn
|
||||||
return id;
|
return id
|
||||||
} else {
|
} else {
|
||||||
return false;
|
return false
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
use(fn: Interceptor) {
|
use(fn: Interceptor) {
|
||||||
this._fns = [...this._fns, fn];
|
this._fns = [...this._fns, fn]
|
||||||
return this._fns.length - 1;
|
return this._fns.length - 1
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// `createInterceptors()` response, meant for external use as it does not
|
// `createInterceptors()` response, meant for external use as it does not
|
||||||
// expose internals
|
// expose internals
|
||||||
export interface Middleware<Req, Res, Err, Options> {
|
export interface Middleware<Req, Res, Err, Options> {
|
||||||
error: Pick<
|
error: Pick<Interceptors<ErrInterceptor<Err, Res, Req, Options>>, "eject" | "use">
|
||||||
Interceptors<ErrInterceptor<Err, Res, Req, Options>>,
|
request: Pick<Interceptors<ReqInterceptor<Req, Options>>, "eject" | "use">
|
||||||
'eject' | 'use'
|
response: Pick<Interceptors<ResInterceptor<Res, Req, Options>>, "eject" | "use">
|
||||||
>;
|
|
||||||
request: Pick<Interceptors<ReqInterceptor<Req, Options>>, 'eject' | 'use'>;
|
|
||||||
response: Pick<
|
|
||||||
Interceptors<ResInterceptor<Res, Req, Options>>,
|
|
||||||
'eject' | 'use'
|
|
||||||
>;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// do not add `Middleware` as return type so we can use _fns internally
|
// do not add `Middleware` as return type so we can use _fns internally
|
||||||
@@ -388,30 +344,30 @@ export const createInterceptors = <Req, Res, Err, Options>() => ({
|
|||||||
error: new Interceptors<ErrInterceptor<Err, Res, Req, Options>>(),
|
error: new Interceptors<ErrInterceptor<Err, Res, Req, Options>>(),
|
||||||
request: new Interceptors<ReqInterceptor<Req, Options>>(),
|
request: new Interceptors<ReqInterceptor<Req, Options>>(),
|
||||||
response: new Interceptors<ResInterceptor<Res, Req, Options>>(),
|
response: new Interceptors<ResInterceptor<Res, Req, Options>>(),
|
||||||
});
|
})
|
||||||
|
|
||||||
const defaultQuerySerializer = createQuerySerializer({
|
const defaultQuerySerializer = createQuerySerializer({
|
||||||
allowReserved: false,
|
allowReserved: false,
|
||||||
array: {
|
array: {
|
||||||
explode: true,
|
explode: true,
|
||||||
style: 'form',
|
style: "form",
|
||||||
},
|
},
|
||||||
object: {
|
object: {
|
||||||
explode: true,
|
explode: true,
|
||||||
style: 'deepObject',
|
style: "deepObject",
|
||||||
},
|
},
|
||||||
});
|
})
|
||||||
|
|
||||||
const defaultHeaders = {
|
const defaultHeaders = {
|
||||||
'Content-Type': 'application/json',
|
"Content-Type": "application/json",
|
||||||
};
|
}
|
||||||
|
|
||||||
export const createConfig = <T extends ClientOptions = ClientOptions>(
|
export const createConfig = <T extends ClientOptions = ClientOptions>(
|
||||||
override: Config<Omit<ClientOptions, keyof T> & T> = {},
|
override: Config<Omit<ClientOptions, keyof T> & T> = {},
|
||||||
): Config<Omit<ClientOptions, keyof T> & T> => ({
|
): Config<Omit<ClientOptions, keyof T> & T> => ({
|
||||||
...jsonBodySerializer,
|
...jsonBodySerializer,
|
||||||
headers: defaultHeaders,
|
headers: defaultHeaders,
|
||||||
parseAs: 'auto',
|
parseAs: "auto",
|
||||||
querySerializer: defaultQuerySerializer,
|
querySerializer: defaultQuerySerializer,
|
||||||
...override,
|
...override,
|
||||||
});
|
})
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
export type AuthToken = string | undefined;
|
export type AuthToken = string | undefined
|
||||||
|
|
||||||
export interface Auth {
|
export interface Auth {
|
||||||
/**
|
/**
|
||||||
@@ -6,35 +6,34 @@ export interface Auth {
|
|||||||
*
|
*
|
||||||
* @default 'header'
|
* @default 'header'
|
||||||
*/
|
*/
|
||||||
in?: 'header' | 'query' | 'cookie';
|
in?: "header" | "query" | "cookie"
|
||||||
/**
|
/**
|
||||||
* Header or query parameter name.
|
* Header or query parameter name.
|
||||||
*
|
*
|
||||||
* @default 'Authorization'
|
* @default 'Authorization'
|
||||||
*/
|
*/
|
||||||
name?: string;
|
name?: string
|
||||||
scheme?: 'basic' | 'bearer';
|
scheme?: "basic" | "bearer"
|
||||||
type: 'apiKey' | 'http';
|
type: "apiKey" | "http"
|
||||||
}
|
}
|
||||||
|
|
||||||
export const getAuthToken = async (
|
export const getAuthToken = async (
|
||||||
auth: Auth,
|
auth: Auth,
|
||||||
callback: ((auth: Auth) => Promise<AuthToken> | AuthToken) | AuthToken,
|
callback: ((auth: Auth) => Promise<AuthToken> | AuthToken) | AuthToken,
|
||||||
): Promise<string | undefined> => {
|
): Promise<string | undefined> => {
|
||||||
const token =
|
const token = typeof callback === "function" ? await callback(auth) : callback
|
||||||
typeof callback === 'function' ? await callback(auth) : callback;
|
|
||||||
|
|
||||||
if (!token) {
|
if (!token) {
|
||||||
return;
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
if (auth.scheme === 'bearer') {
|
if (auth.scheme === "bearer") {
|
||||||
return `Bearer ${token}`;
|
return `Bearer ${token}`
|
||||||
}
|
}
|
||||||
|
|
||||||
if (auth.scheme === 'basic') {
|
if (auth.scheme === "basic") {
|
||||||
return `Basic ${btoa(token)}`;
|
return `Basic ${btoa(token)}`
|
||||||
}
|
}
|
||||||
|
|
||||||
return token;
|
return token
|
||||||
};
|
}
|
||||||
|
|||||||
@@ -1,88 +1,70 @@
|
|||||||
import type {
|
import type { ArrayStyle, ObjectStyle, SerializerOptions } from "./pathSerializer"
|
||||||
ArrayStyle,
|
|
||||||
ObjectStyle,
|
|
||||||
SerializerOptions,
|
|
||||||
} from './pathSerializer';
|
|
||||||
|
|
||||||
export type QuerySerializer = (query: Record<string, unknown>) => string;
|
export type QuerySerializer = (query: Record<string, unknown>) => string
|
||||||
|
|
||||||
export type BodySerializer = (body: any) => any;
|
export type BodySerializer = (body: any) => any
|
||||||
|
|
||||||
export interface QuerySerializerOptions {
|
export interface QuerySerializerOptions {
|
||||||
allowReserved?: boolean;
|
allowReserved?: boolean
|
||||||
array?: SerializerOptions<ArrayStyle>;
|
array?: SerializerOptions<ArrayStyle>
|
||||||
object?: SerializerOptions<ObjectStyle>;
|
object?: SerializerOptions<ObjectStyle>
|
||||||
}
|
}
|
||||||
|
|
||||||
const serializeFormDataPair = (
|
const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => {
|
||||||
data: FormData,
|
if (typeof value === "string" || value instanceof Blob) {
|
||||||
key: string,
|
data.append(key, value)
|
||||||
value: unknown,
|
|
||||||
): void => {
|
|
||||||
if (typeof value === 'string' || value instanceof Blob) {
|
|
||||||
data.append(key, value);
|
|
||||||
} else {
|
} else {
|
||||||
data.append(key, JSON.stringify(value));
|
data.append(key, JSON.stringify(value))
|
||||||
}
|
}
|
||||||
};
|
}
|
||||||
|
|
||||||
const serializeUrlSearchParamsPair = (
|
const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => {
|
||||||
data: URLSearchParams,
|
if (typeof value === "string") {
|
||||||
key: string,
|
data.append(key, value)
|
||||||
value: unknown,
|
|
||||||
): void => {
|
|
||||||
if (typeof value === 'string') {
|
|
||||||
data.append(key, value);
|
|
||||||
} else {
|
} else {
|
||||||
data.append(key, JSON.stringify(value));
|
data.append(key, JSON.stringify(value))
|
||||||
}
|
}
|
||||||
};
|
}
|
||||||
|
|
||||||
export const formDataBodySerializer = {
|
export const formDataBodySerializer = {
|
||||||
bodySerializer: <T extends Record<string, any> | Array<Record<string, any>>>(
|
bodySerializer: <T extends Record<string, any> | Array<Record<string, any>>>(body: T): FormData => {
|
||||||
body: T,
|
const data = new FormData()
|
||||||
): FormData => {
|
|
||||||
const data = new FormData();
|
|
||||||
|
|
||||||
Object.entries(body).forEach(([key, value]) => {
|
Object.entries(body).forEach(([key, value]) => {
|
||||||
if (value === undefined || value === null) {
|
if (value === undefined || value === null) {
|
||||||
return;
|
return
|
||||||
}
|
}
|
||||||
if (Array.isArray(value)) {
|
if (Array.isArray(value)) {
|
||||||
value.forEach((v) => serializeFormDataPair(data, key, v));
|
value.forEach((v) => serializeFormDataPair(data, key, v))
|
||||||
} else {
|
} else {
|
||||||
serializeFormDataPair(data, key, value);
|
serializeFormDataPair(data, key, value)
|
||||||
}
|
}
|
||||||
});
|
})
|
||||||
|
|
||||||
return data;
|
return data
|
||||||
},
|
},
|
||||||
};
|
}
|
||||||
|
|
||||||
export const jsonBodySerializer = {
|
export const jsonBodySerializer = {
|
||||||
bodySerializer: <T>(body: T): string =>
|
bodySerializer: <T>(body: T): string =>
|
||||||
JSON.stringify(body, (_key, value) =>
|
JSON.stringify(body, (_key, value) => (typeof value === "bigint" ? value.toString() : value)),
|
||||||
typeof value === 'bigint' ? value.toString() : value,
|
}
|
||||||
),
|
|
||||||
};
|
|
||||||
|
|
||||||
export const urlSearchParamsBodySerializer = {
|
export const urlSearchParamsBodySerializer = {
|
||||||
bodySerializer: <T extends Record<string, any> | Array<Record<string, any>>>(
|
bodySerializer: <T extends Record<string, any> | Array<Record<string, any>>>(body: T): string => {
|
||||||
body: T,
|
const data = new URLSearchParams()
|
||||||
): string => {
|
|
||||||
const data = new URLSearchParams();
|
|
||||||
|
|
||||||
Object.entries(body).forEach(([key, value]) => {
|
Object.entries(body).forEach(([key, value]) => {
|
||||||
if (value === undefined || value === null) {
|
if (value === undefined || value === null) {
|
||||||
return;
|
return
|
||||||
}
|
}
|
||||||
if (Array.isArray(value)) {
|
if (Array.isArray(value)) {
|
||||||
value.forEach((v) => serializeUrlSearchParamsPair(data, key, v));
|
value.forEach((v) => serializeUrlSearchParamsPair(data, key, v))
|
||||||
} else {
|
} else {
|
||||||
serializeUrlSearchParamsPair(data, key, value);
|
serializeUrlSearchParamsPair(data, key, value)
|
||||||
}
|
}
|
||||||
});
|
})
|
||||||
|
|
||||||
return data.toString();
|
return data.toString()
|
||||||
},
|
},
|
||||||
};
|
}
|
||||||
|
|||||||
@@ -1,142 +1,133 @@
|
|||||||
type Slot = 'body' | 'headers' | 'path' | 'query';
|
type Slot = "body" | "headers" | "path" | "query"
|
||||||
|
|
||||||
export type Field =
|
export type Field =
|
||||||
| {
|
| {
|
||||||
in: Exclude<Slot, 'body'>;
|
in: Exclude<Slot, "body">
|
||||||
/**
|
/**
|
||||||
* Field name. This is the name we want the user to see and use.
|
* Field name. This is the name we want the user to see and use.
|
||||||
*/
|
*/
|
||||||
key: string;
|
key: string
|
||||||
/**
|
/**
|
||||||
* Field mapped name. This is the name we want to use in the request.
|
* Field mapped name. This is the name we want to use in the request.
|
||||||
* If omitted, we use the same value as `key`.
|
* If omitted, we use the same value as `key`.
|
||||||
*/
|
*/
|
||||||
map?: string;
|
map?: string
|
||||||
}
|
}
|
||||||
| {
|
| {
|
||||||
in: Extract<Slot, 'body'>;
|
in: Extract<Slot, "body">
|
||||||
/**
|
/**
|
||||||
* Key isn't required for bodies.
|
* Key isn't required for bodies.
|
||||||
*/
|
*/
|
||||||
key?: string;
|
key?: string
|
||||||
map?: string;
|
map?: string
|
||||||
};
|
}
|
||||||
|
|
||||||
export interface Fields {
|
export interface Fields {
|
||||||
allowExtra?: Partial<Record<Slot, boolean>>;
|
allowExtra?: Partial<Record<Slot, boolean>>
|
||||||
args?: ReadonlyArray<Field>;
|
args?: ReadonlyArray<Field>
|
||||||
}
|
}
|
||||||
|
|
||||||
export type FieldsConfig = ReadonlyArray<Field | Fields>;
|
export type FieldsConfig = ReadonlyArray<Field | Fields>
|
||||||
|
|
||||||
const extraPrefixesMap: Record<string, Slot> = {
|
const extraPrefixesMap: Record<string, Slot> = {
|
||||||
$body_: 'body',
|
$body_: "body",
|
||||||
$headers_: 'headers',
|
$headers_: "headers",
|
||||||
$path_: 'path',
|
$path_: "path",
|
||||||
$query_: 'query',
|
$query_: "query",
|
||||||
};
|
}
|
||||||
const extraPrefixes = Object.entries(extraPrefixesMap);
|
const extraPrefixes = Object.entries(extraPrefixesMap)
|
||||||
|
|
||||||
type KeyMap = Map<
|
type KeyMap = Map<
|
||||||
string,
|
string,
|
||||||
{
|
{
|
||||||
in: Slot;
|
in: Slot
|
||||||
map?: string;
|
map?: string
|
||||||
}
|
}
|
||||||
>;
|
>
|
||||||
|
|
||||||
const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => {
|
const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => {
|
||||||
if (!map) {
|
if (!map) {
|
||||||
map = new Map();
|
map = new Map()
|
||||||
}
|
}
|
||||||
|
|
||||||
for (const config of fields) {
|
for (const config of fields) {
|
||||||
if ('in' in config) {
|
if ("in" in config) {
|
||||||
if (config.key) {
|
if (config.key) {
|
||||||
map.set(config.key, {
|
map.set(config.key, {
|
||||||
in: config.in,
|
in: config.in,
|
||||||
map: config.map,
|
map: config.map,
|
||||||
});
|
})
|
||||||
}
|
}
|
||||||
} else if (config.args) {
|
} else if (config.args) {
|
||||||
buildKeyMap(config.args, map);
|
buildKeyMap(config.args, map)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return map;
|
return map
|
||||||
};
|
}
|
||||||
|
|
||||||
interface Params {
|
interface Params {
|
||||||
body: unknown;
|
body: unknown
|
||||||
headers: Record<string, unknown>;
|
headers: Record<string, unknown>
|
||||||
path: Record<string, unknown>;
|
path: Record<string, unknown>
|
||||||
query: Record<string, unknown>;
|
query: Record<string, unknown>
|
||||||
}
|
}
|
||||||
|
|
||||||
const stripEmptySlots = (params: Params) => {
|
const stripEmptySlots = (params: Params) => {
|
||||||
for (const [slot, value] of Object.entries(params)) {
|
for (const [slot, value] of Object.entries(params)) {
|
||||||
if (value && typeof value === 'object' && !Object.keys(value).length) {
|
if (value && typeof value === "object" && !Object.keys(value).length) {
|
||||||
delete params[slot as Slot];
|
delete params[slot as Slot]
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
};
|
}
|
||||||
|
|
||||||
export const buildClientParams = (
|
export const buildClientParams = (args: ReadonlyArray<unknown>, fields: FieldsConfig) => {
|
||||||
args: ReadonlyArray<unknown>,
|
|
||||||
fields: FieldsConfig,
|
|
||||||
) => {
|
|
||||||
const params: Params = {
|
const params: Params = {
|
||||||
body: {},
|
body: {},
|
||||||
headers: {},
|
headers: {},
|
||||||
path: {},
|
path: {},
|
||||||
query: {},
|
query: {},
|
||||||
};
|
}
|
||||||
|
|
||||||
const map = buildKeyMap(fields);
|
const map = buildKeyMap(fields)
|
||||||
|
|
||||||
let config: FieldsConfig[number] | undefined;
|
let config: FieldsConfig[number] | undefined
|
||||||
|
|
||||||
for (const [index, arg] of args.entries()) {
|
for (const [index, arg] of args.entries()) {
|
||||||
if (fields[index]) {
|
if (fields[index]) {
|
||||||
config = fields[index];
|
config = fields[index]
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!config) {
|
if (!config) {
|
||||||
continue;
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
if ('in' in config) {
|
if ("in" in config) {
|
||||||
if (config.key) {
|
if (config.key) {
|
||||||
const field = map.get(config.key)!;
|
const field = map.get(config.key)!
|
||||||
const name = field.map || config.key;
|
const name = field.map || config.key
|
||||||
(params[field.in] as Record<string, unknown>)[name] = arg;
|
;(params[field.in] as Record<string, unknown>)[name] = arg
|
||||||
} else {
|
} else {
|
||||||
params.body = arg;
|
params.body = arg
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
for (const [key, value] of Object.entries(arg ?? {})) {
|
for (const [key, value] of Object.entries(arg ?? {})) {
|
||||||
const field = map.get(key);
|
const field = map.get(key)
|
||||||
|
|
||||||
if (field) {
|
if (field) {
|
||||||
const name = field.map || key;
|
const name = field.map || key
|
||||||
(params[field.in] as Record<string, unknown>)[name] = value;
|
;(params[field.in] as Record<string, unknown>)[name] = value
|
||||||
} else {
|
} else {
|
||||||
const extra = extraPrefixes.find(([prefix]) =>
|
const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix))
|
||||||
key.startsWith(prefix),
|
|
||||||
);
|
|
||||||
|
|
||||||
if (extra) {
|
if (extra) {
|
||||||
const [prefix, slot] = extra;
|
const [prefix, slot] = extra
|
||||||
(params[slot] as Record<string, unknown>)[
|
;(params[slot] as Record<string, unknown>)[key.slice(prefix.length)] = value
|
||||||
key.slice(prefix.length)
|
|
||||||
] = value;
|
|
||||||
} else {
|
} else {
|
||||||
for (const [slot, allowed] of Object.entries(
|
for (const [slot, allowed] of Object.entries(config.allowExtra ?? {})) {
|
||||||
config.allowExtra ?? {},
|
|
||||||
)) {
|
|
||||||
if (allowed) {
|
if (allowed) {
|
||||||
(params[slot as Slot] as Record<string, unknown>)[key] = value;
|
;(params[slot as Slot] as Record<string, unknown>)[key] = value
|
||||||
break;
|
break
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -145,7 +136,7 @@ export const buildClientParams = (
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
stripEmptySlots(params);
|
stripEmptySlots(params)
|
||||||
|
|
||||||
return params;
|
return params
|
||||||
};
|
}
|
||||||
|
|||||||
@@ -1,68 +1,66 @@
|
|||||||
interface SerializeOptions<T>
|
interface SerializeOptions<T> extends SerializePrimitiveOptions, SerializerOptions<T> {}
|
||||||
extends SerializePrimitiveOptions,
|
|
||||||
SerializerOptions<T> {}
|
|
||||||
|
|
||||||
interface SerializePrimitiveOptions {
|
interface SerializePrimitiveOptions {
|
||||||
allowReserved?: boolean;
|
allowReserved?: boolean
|
||||||
name: string;
|
name: string
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface SerializerOptions<T> {
|
export interface SerializerOptions<T> {
|
||||||
/**
|
/**
|
||||||
* @default true
|
* @default true
|
||||||
*/
|
*/
|
||||||
explode: boolean;
|
explode: boolean
|
||||||
style: T;
|
style: T
|
||||||
}
|
}
|
||||||
|
|
||||||
export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited';
|
export type ArrayStyle = "form" | "spaceDelimited" | "pipeDelimited"
|
||||||
export type ArraySeparatorStyle = ArrayStyle | MatrixStyle;
|
export type ArraySeparatorStyle = ArrayStyle | MatrixStyle
|
||||||
type MatrixStyle = 'label' | 'matrix' | 'simple';
|
type MatrixStyle = "label" | "matrix" | "simple"
|
||||||
export type ObjectStyle = 'form' | 'deepObject';
|
export type ObjectStyle = "form" | "deepObject"
|
||||||
type ObjectSeparatorStyle = ObjectStyle | MatrixStyle;
|
type ObjectSeparatorStyle = ObjectStyle | MatrixStyle
|
||||||
|
|
||||||
interface SerializePrimitiveParam extends SerializePrimitiveOptions {
|
interface SerializePrimitiveParam extends SerializePrimitiveOptions {
|
||||||
value: string;
|
value: string
|
||||||
}
|
}
|
||||||
|
|
||||||
export const separatorArrayExplode = (style: ArraySeparatorStyle) => {
|
export const separatorArrayExplode = (style: ArraySeparatorStyle) => {
|
||||||
switch (style) {
|
switch (style) {
|
||||||
case 'label':
|
case "label":
|
||||||
return '.';
|
return "."
|
||||||
case 'matrix':
|
case "matrix":
|
||||||
return ';';
|
return ";"
|
||||||
case 'simple':
|
case "simple":
|
||||||
return ',';
|
return ","
|
||||||
default:
|
default:
|
||||||
return '&';
|
return "&"
|
||||||
}
|
}
|
||||||
};
|
}
|
||||||
|
|
||||||
export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => {
|
export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => {
|
||||||
switch (style) {
|
switch (style) {
|
||||||
case 'form':
|
case "form":
|
||||||
return ',';
|
return ","
|
||||||
case 'pipeDelimited':
|
case "pipeDelimited":
|
||||||
return '|';
|
return "|"
|
||||||
case 'spaceDelimited':
|
case "spaceDelimited":
|
||||||
return '%20';
|
return "%20"
|
||||||
default:
|
default:
|
||||||
return ',';
|
return ","
|
||||||
}
|
}
|
||||||
};
|
}
|
||||||
|
|
||||||
export const separatorObjectExplode = (style: ObjectSeparatorStyle) => {
|
export const separatorObjectExplode = (style: ObjectSeparatorStyle) => {
|
||||||
switch (style) {
|
switch (style) {
|
||||||
case 'label':
|
case "label":
|
||||||
return '.';
|
return "."
|
||||||
case 'matrix':
|
case "matrix":
|
||||||
return ';';
|
return ";"
|
||||||
case 'simple':
|
case "simple":
|
||||||
return ',';
|
return ","
|
||||||
default:
|
default:
|
||||||
return '&';
|
return "&"
|
||||||
}
|
}
|
||||||
};
|
}
|
||||||
|
|
||||||
export const serializeArrayParam = ({
|
export const serializeArrayParam = ({
|
||||||
allowReserved,
|
allowReserved,
|
||||||
@@ -71,60 +69,54 @@ export const serializeArrayParam = ({
|
|||||||
style,
|
style,
|
||||||
value,
|
value,
|
||||||
}: SerializeOptions<ArraySeparatorStyle> & {
|
}: SerializeOptions<ArraySeparatorStyle> & {
|
||||||
value: unknown[];
|
value: unknown[]
|
||||||
}) => {
|
}) => {
|
||||||
if (!explode) {
|
if (!explode) {
|
||||||
const joinedValues = (
|
const joinedValues = (allowReserved ? value : value.map((v) => encodeURIComponent(v as string))).join(
|
||||||
allowReserved ? value : value.map((v) => encodeURIComponent(v as string))
|
separatorArrayNoExplode(style),
|
||||||
).join(separatorArrayNoExplode(style));
|
)
|
||||||
switch (style) {
|
switch (style) {
|
||||||
case 'label':
|
case "label":
|
||||||
return `.${joinedValues}`;
|
return `.${joinedValues}`
|
||||||
case 'matrix':
|
case "matrix":
|
||||||
return `;${name}=${joinedValues}`;
|
return `;${name}=${joinedValues}`
|
||||||
case 'simple':
|
case "simple":
|
||||||
return joinedValues;
|
return joinedValues
|
||||||
default:
|
default:
|
||||||
return `${name}=${joinedValues}`;
|
return `${name}=${joinedValues}`
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const separator = separatorArrayExplode(style);
|
const separator = separatorArrayExplode(style)
|
||||||
const joinedValues = value
|
const joinedValues = value
|
||||||
.map((v) => {
|
.map((v) => {
|
||||||
if (style === 'label' || style === 'simple') {
|
if (style === "label" || style === "simple") {
|
||||||
return allowReserved ? v : encodeURIComponent(v as string);
|
return allowReserved ? v : encodeURIComponent(v as string)
|
||||||
}
|
}
|
||||||
|
|
||||||
return serializePrimitiveParam({
|
return serializePrimitiveParam({
|
||||||
allowReserved,
|
allowReserved,
|
||||||
name,
|
name,
|
||||||
value: v as string,
|
value: v as string,
|
||||||
});
|
|
||||||
})
|
})
|
||||||
.join(separator);
|
})
|
||||||
return style === 'label' || style === 'matrix'
|
.join(separator)
|
||||||
? separator + joinedValues
|
return style === "label" || style === "matrix" ? separator + joinedValues : joinedValues
|
||||||
: joinedValues;
|
}
|
||||||
};
|
|
||||||
|
|
||||||
export const serializePrimitiveParam = ({
|
export const serializePrimitiveParam = ({ allowReserved, name, value }: SerializePrimitiveParam) => {
|
||||||
allowReserved,
|
|
||||||
name,
|
|
||||||
value,
|
|
||||||
}: SerializePrimitiveParam) => {
|
|
||||||
if (value === undefined || value === null) {
|
if (value === undefined || value === null) {
|
||||||
return '';
|
return ""
|
||||||
}
|
}
|
||||||
|
|
||||||
if (typeof value === 'object') {
|
if (typeof value === "object") {
|
||||||
throw new Error(
|
throw new Error(
|
||||||
'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.',
|
"Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.",
|
||||||
);
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
return `${name}=${allowReserved ? value : encodeURIComponent(value)}`;
|
return `${name}=${allowReserved ? value : encodeURIComponent(value)}`
|
||||||
};
|
}
|
||||||
|
|
||||||
export const serializeObjectParam = ({
|
export const serializeObjectParam = ({
|
||||||
allowReserved,
|
allowReserved,
|
||||||
@@ -134,46 +126,40 @@ export const serializeObjectParam = ({
|
|||||||
value,
|
value,
|
||||||
valueOnly,
|
valueOnly,
|
||||||
}: SerializeOptions<ObjectSeparatorStyle> & {
|
}: SerializeOptions<ObjectSeparatorStyle> & {
|
||||||
value: Record<string, unknown> | Date;
|
value: Record<string, unknown> | Date
|
||||||
valueOnly?: boolean;
|
valueOnly?: boolean
|
||||||
}) => {
|
}) => {
|
||||||
if (value instanceof Date) {
|
if (value instanceof Date) {
|
||||||
return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`;
|
return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`
|
||||||
}
|
}
|
||||||
|
|
||||||
if (style !== 'deepObject' && !explode) {
|
if (style !== "deepObject" && !explode) {
|
||||||
let values: string[] = [];
|
let values: string[] = []
|
||||||
Object.entries(value).forEach(([key, v]) => {
|
Object.entries(value).forEach(([key, v]) => {
|
||||||
values = [
|
values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)]
|
||||||
...values,
|
})
|
||||||
key,
|
const joinedValues = values.join(",")
|
||||||
allowReserved ? (v as string) : encodeURIComponent(v as string),
|
|
||||||
];
|
|
||||||
});
|
|
||||||
const joinedValues = values.join(',');
|
|
||||||
switch (style) {
|
switch (style) {
|
||||||
case 'form':
|
case "form":
|
||||||
return `${name}=${joinedValues}`;
|
return `${name}=${joinedValues}`
|
||||||
case 'label':
|
case "label":
|
||||||
return `.${joinedValues}`;
|
return `.${joinedValues}`
|
||||||
case 'matrix':
|
case "matrix":
|
||||||
return `;${name}=${joinedValues}`;
|
return `;${name}=${joinedValues}`
|
||||||
default:
|
default:
|
||||||
return joinedValues;
|
return joinedValues
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const separator = separatorObjectExplode(style);
|
const separator = separatorObjectExplode(style)
|
||||||
const joinedValues = Object.entries(value)
|
const joinedValues = Object.entries(value)
|
||||||
.map(([key, v]) =>
|
.map(([key, v]) =>
|
||||||
serializePrimitiveParam({
|
serializePrimitiveParam({
|
||||||
allowReserved,
|
allowReserved,
|
||||||
name: style === 'deepObject' ? `${name}[${key}]` : key,
|
name: style === "deepObject" ? `${name}[${key}]` : key,
|
||||||
value: v as string,
|
value: v as string,
|
||||||
}),
|
}),
|
||||||
)
|
)
|
||||||
.join(separator);
|
.join(separator)
|
||||||
return style === 'label' || style === 'matrix'
|
return style === "label" || style === "matrix" ? separator + joinedValues : joinedValues
|
||||||
? separator + joinedValues
|
}
|
||||||
: joinedValues;
|
|
||||||
};
|
|
||||||
|
|||||||
@@ -1,32 +1,23 @@
|
|||||||
import type { Auth, AuthToken } from './auth';
|
import type { Auth, AuthToken } from "./auth"
|
||||||
import type {
|
import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from "./bodySerializer"
|
||||||
BodySerializer,
|
|
||||||
QuerySerializer,
|
|
||||||
QuerySerializerOptions,
|
|
||||||
} from './bodySerializer';
|
|
||||||
|
|
||||||
export interface Client<
|
export interface Client<RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never> {
|
||||||
RequestFn = never,
|
|
||||||
Config = unknown,
|
|
||||||
MethodFn = never,
|
|
||||||
BuildUrlFn = never,
|
|
||||||
> {
|
|
||||||
/**
|
/**
|
||||||
* Returns the final request URL.
|
* Returns the final request URL.
|
||||||
*/
|
*/
|
||||||
buildUrl: BuildUrlFn;
|
buildUrl: BuildUrlFn
|
||||||
connect: MethodFn;
|
connect: MethodFn
|
||||||
delete: MethodFn;
|
delete: MethodFn
|
||||||
get: MethodFn;
|
get: MethodFn
|
||||||
getConfig: () => Config;
|
getConfig: () => Config
|
||||||
head: MethodFn;
|
head: MethodFn
|
||||||
options: MethodFn;
|
options: MethodFn
|
||||||
patch: MethodFn;
|
patch: MethodFn
|
||||||
post: MethodFn;
|
post: MethodFn
|
||||||
put: MethodFn;
|
put: MethodFn
|
||||||
request: RequestFn;
|
request: RequestFn
|
||||||
setConfig: (config: Config) => Config;
|
setConfig: (config: Config) => Config
|
||||||
trace: MethodFn;
|
trace: MethodFn
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface Config {
|
export interface Config {
|
||||||
@@ -34,12 +25,12 @@ export interface Config {
|
|||||||
* Auth token or a function returning auth token. The resolved value will be
|
* Auth token or a function returning auth token. The resolved value will be
|
||||||
* added to the request payload as defined by its `security` array.
|
* added to the request payload as defined by its `security` array.
|
||||||
*/
|
*/
|
||||||
auth?: ((auth: Auth) => Promise<AuthToken> | AuthToken) | AuthToken;
|
auth?: ((auth: Auth) => Promise<AuthToken> | AuthToken) | AuthToken
|
||||||
/**
|
/**
|
||||||
* A function for serializing request body parameter. By default,
|
* A function for serializing request body parameter. By default,
|
||||||
* {@link JSON.stringify()} will be used.
|
* {@link JSON.stringify()} will be used.
|
||||||
*/
|
*/
|
||||||
bodySerializer?: BodySerializer | null;
|
bodySerializer?: BodySerializer | null
|
||||||
/**
|
/**
|
||||||
* An object containing any HTTP headers that you want to pre-populate your
|
* An object containing any HTTP headers that you want to pre-populate your
|
||||||
* `Headers` object with.
|
* `Headers` object with.
|
||||||
@@ -47,32 +38,14 @@ export interface Config {
|
|||||||
* {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more}
|
* {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more}
|
||||||
*/
|
*/
|
||||||
headers?:
|
headers?:
|
||||||
| RequestInit['headers']
|
| RequestInit["headers"]
|
||||||
| Record<
|
| Record<string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown>
|
||||||
string,
|
|
||||||
| string
|
|
||||||
| number
|
|
||||||
| boolean
|
|
||||||
| (string | number | boolean)[]
|
|
||||||
| null
|
|
||||||
| undefined
|
|
||||||
| unknown
|
|
||||||
>;
|
|
||||||
/**
|
/**
|
||||||
* The request method.
|
* The request method.
|
||||||
*
|
*
|
||||||
* {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more}
|
* {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more}
|
||||||
*/
|
*/
|
||||||
method?:
|
method?: "CONNECT" | "DELETE" | "GET" | "HEAD" | "OPTIONS" | "PATCH" | "POST" | "PUT" | "TRACE"
|
||||||
| 'CONNECT'
|
|
||||||
| 'DELETE'
|
|
||||||
| 'GET'
|
|
||||||
| 'HEAD'
|
|
||||||
| 'OPTIONS'
|
|
||||||
| 'PATCH'
|
|
||||||
| 'POST'
|
|
||||||
| 'PUT'
|
|
||||||
| 'TRACE';
|
|
||||||
/**
|
/**
|
||||||
* A function for serializing request query parameters. By default, arrays
|
* A function for serializing request query parameters. By default, arrays
|
||||||
* will be exploded in form style, objects will be exploded in deepObject
|
* will be exploded in form style, objects will be exploded in deepObject
|
||||||
@@ -83,24 +56,24 @@ export interface Config {
|
|||||||
*
|
*
|
||||||
* {@link https://swagger.io/docs/specification/serialization/#query View examples}
|
* {@link https://swagger.io/docs/specification/serialization/#query View examples}
|
||||||
*/
|
*/
|
||||||
querySerializer?: QuerySerializer | QuerySerializerOptions;
|
querySerializer?: QuerySerializer | QuerySerializerOptions
|
||||||
/**
|
/**
|
||||||
* A function validating request data. This is useful if you want to ensure
|
* 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 request conforms to the desired shape, so it can be safely sent to
|
||||||
* the server.
|
* the server.
|
||||||
*/
|
*/
|
||||||
requestValidator?: (data: unknown) => Promise<unknown>;
|
requestValidator?: (data: unknown) => Promise<unknown>
|
||||||
/**
|
/**
|
||||||
* A function transforming response data before it's returned. This is useful
|
* A function transforming response data before it's returned. This is useful
|
||||||
* for post-processing data, e.g. converting ISO strings into Date objects.
|
* for post-processing data, e.g. converting ISO strings into Date objects.
|
||||||
*/
|
*/
|
||||||
responseTransformer?: (data: unknown) => Promise<unknown>;
|
responseTransformer?: (data: unknown) => Promise<unknown>
|
||||||
/**
|
/**
|
||||||
* A function validating response data. This is useful if you want to ensure
|
* 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 response conforms to the desired shape, so it can be safely passed to
|
||||||
* the transformers and returned to the user.
|
* the transformers and returned to the user.
|
||||||
*/
|
*/
|
||||||
responseValidator?: (data: unknown) => Promise<unknown>;
|
responseValidator?: (data: unknown) => Promise<unknown>
|
||||||
}
|
}
|
||||||
|
|
||||||
type IsExactlyNeverOrNeverUndefined<T> = [T] extends [never]
|
type IsExactlyNeverOrNeverUndefined<T> = [T] extends [never]
|
||||||
@@ -109,10 +82,8 @@ type IsExactlyNeverOrNeverUndefined<T> = [T] extends [never]
|
|||||||
? [undefined] extends [T]
|
? [undefined] extends [T]
|
||||||
? false
|
? false
|
||||||
: true
|
: true
|
||||||
: false;
|
: false
|
||||||
|
|
||||||
export type OmitNever<T extends Record<string, unknown>> = {
|
export type OmitNever<T extends Record<string, unknown>> = {
|
||||||
[K in keyof T as IsExactlyNeverOrNeverUndefined<T[K]> extends true
|
[K in keyof T as IsExactlyNeverOrNeverUndefined<T[K]> extends true ? never : K]: T[K]
|
||||||
? never
|
}
|
||||||
: K]: T[K];
|
|
||||||
};
|
|
||||||
|
|||||||
@@ -1,31 +1,102 @@
|
|||||||
// This file is auto-generated by @hey-api/openapi-ts
|
// This file is auto-generated by @hey-api/openapi-ts
|
||||||
|
|
||||||
import type { Options as ClientOptions, TDataShape, Client } from './client';
|
import type { Options as ClientOptions, TDataShape, Client } from "./client"
|
||||||
import type { EventSubscribeData, EventSubscribeResponses, AppGetData, AppGetResponses, AppInitData, AppInitResponses, ConfigGetData, ConfigGetResponses, SessionListData, SessionListResponses, SessionCreateData, SessionCreateResponses, SessionCreateErrors, SessionDeleteData, SessionDeleteResponses, SessionInitData, SessionInitResponses, SessionAbortData, SessionAbortResponses, SessionUnshareData, SessionUnshareResponses, SessionShareData, SessionShareResponses, SessionSummarizeData, SessionSummarizeResponses, SessionMessagesData, SessionMessagesResponses, SessionChatData, SessionChatResponses, SessionMessageData, SessionMessageResponses, SessionRevertData, SessionRevertResponses, SessionUnrevertData, SessionUnrevertResponses, PostSessionByIdPermissionsByPermissionIdData, PostSessionByIdPermissionsByPermissionIdResponses, ConfigProvidersData, ConfigProvidersResponses, FindTextData, FindTextResponses, FindFilesData, FindFilesResponses, FindSymbolsData, FindSymbolsResponses, FileReadData, FileReadResponses, FileStatusData, FileStatusResponses, AppLogData, AppLogResponses, AppModesData, AppModesResponses, TuiAppendPromptData, TuiAppendPromptResponses, TuiOpenHelpData, TuiOpenHelpResponses, TuiOpenSessionsData, TuiOpenSessionsResponses, TuiOpenThemesData, TuiOpenThemesResponses, TuiOpenModelsData, TuiOpenModelsResponses, TuiSubmitPromptData, TuiSubmitPromptResponses, TuiClearPromptData, TuiClearPromptResponses, TuiExecuteCommandData, TuiExecuteCommandResponses } from './types.gen';
|
import type {
|
||||||
import { client as _heyApiClient } from './client.gen';
|
EventSubscribeData,
|
||||||
|
EventSubscribeResponses,
|
||||||
|
AppGetData,
|
||||||
|
AppGetResponses,
|
||||||
|
AppInitData,
|
||||||
|
AppInitResponses,
|
||||||
|
ConfigGetData,
|
||||||
|
ConfigGetResponses,
|
||||||
|
SessionListData,
|
||||||
|
SessionListResponses,
|
||||||
|
SessionCreateData,
|
||||||
|
SessionCreateResponses,
|
||||||
|
SessionCreateErrors,
|
||||||
|
SessionDeleteData,
|
||||||
|
SessionDeleteResponses,
|
||||||
|
SessionInitData,
|
||||||
|
SessionInitResponses,
|
||||||
|
SessionAbortData,
|
||||||
|
SessionAbortResponses,
|
||||||
|
SessionUnshareData,
|
||||||
|
SessionUnshareResponses,
|
||||||
|
SessionShareData,
|
||||||
|
SessionShareResponses,
|
||||||
|
SessionSummarizeData,
|
||||||
|
SessionSummarizeResponses,
|
||||||
|
SessionMessagesData,
|
||||||
|
SessionMessagesResponses,
|
||||||
|
SessionChatData,
|
||||||
|
SessionChatResponses,
|
||||||
|
SessionMessageData,
|
||||||
|
SessionMessageResponses,
|
||||||
|
SessionRevertData,
|
||||||
|
SessionRevertResponses,
|
||||||
|
SessionUnrevertData,
|
||||||
|
SessionUnrevertResponses,
|
||||||
|
PostSessionByIdPermissionsByPermissionIdData,
|
||||||
|
PostSessionByIdPermissionsByPermissionIdResponses,
|
||||||
|
ConfigProvidersData,
|
||||||
|
ConfigProvidersResponses,
|
||||||
|
FindTextData,
|
||||||
|
FindTextResponses,
|
||||||
|
FindFilesData,
|
||||||
|
FindFilesResponses,
|
||||||
|
FindSymbolsData,
|
||||||
|
FindSymbolsResponses,
|
||||||
|
FileReadData,
|
||||||
|
FileReadResponses,
|
||||||
|
FileStatusData,
|
||||||
|
FileStatusResponses,
|
||||||
|
AppLogData,
|
||||||
|
AppLogResponses,
|
||||||
|
AppModesData,
|
||||||
|
AppModesResponses,
|
||||||
|
TuiAppendPromptData,
|
||||||
|
TuiAppendPromptResponses,
|
||||||
|
TuiOpenHelpData,
|
||||||
|
TuiOpenHelpResponses,
|
||||||
|
TuiOpenSessionsData,
|
||||||
|
TuiOpenSessionsResponses,
|
||||||
|
TuiOpenThemesData,
|
||||||
|
TuiOpenThemesResponses,
|
||||||
|
TuiOpenModelsData,
|
||||||
|
TuiOpenModelsResponses,
|
||||||
|
TuiSubmitPromptData,
|
||||||
|
TuiSubmitPromptResponses,
|
||||||
|
TuiClearPromptData,
|
||||||
|
TuiClearPromptResponses,
|
||||||
|
TuiExecuteCommandData,
|
||||||
|
TuiExecuteCommandResponses,
|
||||||
|
} from "./types.gen"
|
||||||
|
import { client as _heyApiClient } from "./client.gen"
|
||||||
|
|
||||||
export type Options<TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean> = ClientOptions<TData, ThrowOnError> & {
|
export type Options<TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean> = ClientOptions<
|
||||||
|
TData,
|
||||||
|
ThrowOnError
|
||||||
|
> & {
|
||||||
/**
|
/**
|
||||||
* You can provide a client instance returned by `createClient()` instead of
|
* You can provide a client instance returned by `createClient()` instead of
|
||||||
* individual options. This might be also useful if you want to implement a
|
* individual options. This might be also useful if you want to implement a
|
||||||
* custom client.
|
* custom client.
|
||||||
*/
|
*/
|
||||||
client?: Client;
|
client?: Client
|
||||||
/**
|
/**
|
||||||
* You can pass arbitrary values through the `meta` object. This can be
|
* You can pass arbitrary values through the `meta` object. This can be
|
||||||
* used to access values that aren't defined as part of the SDK function.
|
* used to access values that aren't defined as part of the SDK function.
|
||||||
*/
|
*/
|
||||||
meta?: Record<string, unknown>;
|
meta?: Record<string, unknown>
|
||||||
};
|
}
|
||||||
|
|
||||||
class _HeyApiClient {
|
class _HeyApiClient {
|
||||||
protected _client: Client = _heyApiClient;
|
protected _client: Client = _heyApiClient
|
||||||
|
|
||||||
constructor(args?: {
|
constructor(args?: { client?: Client }) {
|
||||||
client?: Client;
|
|
||||||
}) {
|
|
||||||
if (args?.client) {
|
if (args?.client) {
|
||||||
this._client = args.client;
|
this._client = args.client
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -36,9 +107,9 @@ class Event extends _HeyApiClient {
|
|||||||
*/
|
*/
|
||||||
public subscribe<ThrowOnError extends boolean = false>(options?: Options<EventSubscribeData, ThrowOnError>) {
|
public subscribe<ThrowOnError extends boolean = false>(options?: Options<EventSubscribeData, ThrowOnError>) {
|
||||||
return (options?.client ?? this._client).get<EventSubscribeResponses, unknown, ThrowOnError>({
|
return (options?.client ?? this._client).get<EventSubscribeResponses, unknown, ThrowOnError>({
|
||||||
url: '/event',
|
url: "/event",
|
||||||
...options
|
...options,
|
||||||
});
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -48,9 +119,9 @@ class App extends _HeyApiClient {
|
|||||||
*/
|
*/
|
||||||
public get<ThrowOnError extends boolean = false>(options?: Options<AppGetData, ThrowOnError>) {
|
public get<ThrowOnError extends boolean = false>(options?: Options<AppGetData, ThrowOnError>) {
|
||||||
return (options?.client ?? this._client).get<AppGetResponses, unknown, ThrowOnError>({
|
return (options?.client ?? this._client).get<AppGetResponses, unknown, ThrowOnError>({
|
||||||
url: '/app',
|
url: "/app",
|
||||||
...options
|
...options,
|
||||||
});
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -58,9 +129,9 @@ class App extends _HeyApiClient {
|
|||||||
*/
|
*/
|
||||||
public init<ThrowOnError extends boolean = false>(options?: Options<AppInitData, ThrowOnError>) {
|
public init<ThrowOnError extends boolean = false>(options?: Options<AppInitData, ThrowOnError>) {
|
||||||
return (options?.client ?? this._client).post<AppInitResponses, unknown, ThrowOnError>({
|
return (options?.client ?? this._client).post<AppInitResponses, unknown, ThrowOnError>({
|
||||||
url: '/app/init',
|
url: "/app/init",
|
||||||
...options
|
...options,
|
||||||
});
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -68,13 +139,13 @@ class App extends _HeyApiClient {
|
|||||||
*/
|
*/
|
||||||
public log<ThrowOnError extends boolean = false>(options?: Options<AppLogData, ThrowOnError>) {
|
public log<ThrowOnError extends boolean = false>(options?: Options<AppLogData, ThrowOnError>) {
|
||||||
return (options?.client ?? this._client).post<AppLogResponses, unknown, ThrowOnError>({
|
return (options?.client ?? this._client).post<AppLogResponses, unknown, ThrowOnError>({
|
||||||
url: '/log',
|
url: "/log",
|
||||||
...options,
|
...options,
|
||||||
headers: {
|
headers: {
|
||||||
'Content-Type': 'application/json',
|
"Content-Type": "application/json",
|
||||||
...options?.headers
|
...options?.headers,
|
||||||
}
|
},
|
||||||
});
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -82,9 +153,9 @@ class App extends _HeyApiClient {
|
|||||||
*/
|
*/
|
||||||
public modes<ThrowOnError extends boolean = false>(options?: Options<AppModesData, ThrowOnError>) {
|
public modes<ThrowOnError extends boolean = false>(options?: Options<AppModesData, ThrowOnError>) {
|
||||||
return (options?.client ?? this._client).get<AppModesResponses, unknown, ThrowOnError>({
|
return (options?.client ?? this._client).get<AppModesResponses, unknown, ThrowOnError>({
|
||||||
url: '/mode',
|
url: "/mode",
|
||||||
...options
|
...options,
|
||||||
});
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -94,9 +165,9 @@ class Config extends _HeyApiClient {
|
|||||||
*/
|
*/
|
||||||
public get<ThrowOnError extends boolean = false>(options?: Options<ConfigGetData, ThrowOnError>) {
|
public get<ThrowOnError extends boolean = false>(options?: Options<ConfigGetData, ThrowOnError>) {
|
||||||
return (options?.client ?? this._client).get<ConfigGetResponses, unknown, ThrowOnError>({
|
return (options?.client ?? this._client).get<ConfigGetResponses, unknown, ThrowOnError>({
|
||||||
url: '/config',
|
url: "/config",
|
||||||
...options
|
...options,
|
||||||
});
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -104,9 +175,9 @@ class Config extends _HeyApiClient {
|
|||||||
*/
|
*/
|
||||||
public providers<ThrowOnError extends boolean = false>(options?: Options<ConfigProvidersData, ThrowOnError>) {
|
public providers<ThrowOnError extends boolean = false>(options?: Options<ConfigProvidersData, ThrowOnError>) {
|
||||||
return (options?.client ?? this._client).get<ConfigProvidersResponses, unknown, ThrowOnError>({
|
return (options?.client ?? this._client).get<ConfigProvidersResponses, unknown, ThrowOnError>({
|
||||||
url: '/config/providers',
|
url: "/config/providers",
|
||||||
...options
|
...options,
|
||||||
});
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -116,9 +187,9 @@ class Session extends _HeyApiClient {
|
|||||||
*/
|
*/
|
||||||
public list<ThrowOnError extends boolean = false>(options?: Options<SessionListData, ThrowOnError>) {
|
public list<ThrowOnError extends boolean = false>(options?: Options<SessionListData, ThrowOnError>) {
|
||||||
return (options?.client ?? this._client).get<SessionListResponses, unknown, ThrowOnError>({
|
return (options?.client ?? this._client).get<SessionListResponses, unknown, ThrowOnError>({
|
||||||
url: '/session',
|
url: "/session",
|
||||||
...options
|
...options,
|
||||||
});
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -126,9 +197,9 @@ class Session extends _HeyApiClient {
|
|||||||
*/
|
*/
|
||||||
public create<ThrowOnError extends boolean = false>(options?: Options<SessionCreateData, ThrowOnError>) {
|
public create<ThrowOnError extends boolean = false>(options?: Options<SessionCreateData, ThrowOnError>) {
|
||||||
return (options?.client ?? this._client).post<SessionCreateResponses, SessionCreateErrors, ThrowOnError>({
|
return (options?.client ?? this._client).post<SessionCreateResponses, SessionCreateErrors, ThrowOnError>({
|
||||||
url: '/session',
|
url: "/session",
|
||||||
...options
|
...options,
|
||||||
});
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -136,9 +207,9 @@ class Session extends _HeyApiClient {
|
|||||||
*/
|
*/
|
||||||
public delete<ThrowOnError extends boolean = false>(options: Options<SessionDeleteData, ThrowOnError>) {
|
public delete<ThrowOnError extends boolean = false>(options: Options<SessionDeleteData, ThrowOnError>) {
|
||||||
return (options.client ?? this._client).delete<SessionDeleteResponses, unknown, ThrowOnError>({
|
return (options.client ?? this._client).delete<SessionDeleteResponses, unknown, ThrowOnError>({
|
||||||
url: '/session/{id}',
|
url: "/session/{id}",
|
||||||
...options
|
...options,
|
||||||
});
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -146,13 +217,13 @@ class Session extends _HeyApiClient {
|
|||||||
*/
|
*/
|
||||||
public init<ThrowOnError extends boolean = false>(options: Options<SessionInitData, ThrowOnError>) {
|
public init<ThrowOnError extends boolean = false>(options: Options<SessionInitData, ThrowOnError>) {
|
||||||
return (options.client ?? this._client).post<SessionInitResponses, unknown, ThrowOnError>({
|
return (options.client ?? this._client).post<SessionInitResponses, unknown, ThrowOnError>({
|
||||||
url: '/session/{id}/init',
|
url: "/session/{id}/init",
|
||||||
...options,
|
...options,
|
||||||
headers: {
|
headers: {
|
||||||
'Content-Type': 'application/json',
|
"Content-Type": "application/json",
|
||||||
...options.headers
|
...options.headers,
|
||||||
}
|
},
|
||||||
});
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -160,9 +231,9 @@ class Session extends _HeyApiClient {
|
|||||||
*/
|
*/
|
||||||
public abort<ThrowOnError extends boolean = false>(options: Options<SessionAbortData, ThrowOnError>) {
|
public abort<ThrowOnError extends boolean = false>(options: Options<SessionAbortData, ThrowOnError>) {
|
||||||
return (options.client ?? this._client).post<SessionAbortResponses, unknown, ThrowOnError>({
|
return (options.client ?? this._client).post<SessionAbortResponses, unknown, ThrowOnError>({
|
||||||
url: '/session/{id}/abort',
|
url: "/session/{id}/abort",
|
||||||
...options
|
...options,
|
||||||
});
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -170,9 +241,9 @@ class Session extends _HeyApiClient {
|
|||||||
*/
|
*/
|
||||||
public unshare<ThrowOnError extends boolean = false>(options: Options<SessionUnshareData, ThrowOnError>) {
|
public unshare<ThrowOnError extends boolean = false>(options: Options<SessionUnshareData, ThrowOnError>) {
|
||||||
return (options.client ?? this._client).delete<SessionUnshareResponses, unknown, ThrowOnError>({
|
return (options.client ?? this._client).delete<SessionUnshareResponses, unknown, ThrowOnError>({
|
||||||
url: '/session/{id}/share',
|
url: "/session/{id}/share",
|
||||||
...options
|
...options,
|
||||||
});
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -180,9 +251,9 @@ class Session extends _HeyApiClient {
|
|||||||
*/
|
*/
|
||||||
public share<ThrowOnError extends boolean = false>(options: Options<SessionShareData, ThrowOnError>) {
|
public share<ThrowOnError extends boolean = false>(options: Options<SessionShareData, ThrowOnError>) {
|
||||||
return (options.client ?? this._client).post<SessionShareResponses, unknown, ThrowOnError>({
|
return (options.client ?? this._client).post<SessionShareResponses, unknown, ThrowOnError>({
|
||||||
url: '/session/{id}/share',
|
url: "/session/{id}/share",
|
||||||
...options
|
...options,
|
||||||
});
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -190,13 +261,13 @@ class Session extends _HeyApiClient {
|
|||||||
*/
|
*/
|
||||||
public summarize<ThrowOnError extends boolean = false>(options: Options<SessionSummarizeData, ThrowOnError>) {
|
public summarize<ThrowOnError extends boolean = false>(options: Options<SessionSummarizeData, ThrowOnError>) {
|
||||||
return (options.client ?? this._client).post<SessionSummarizeResponses, unknown, ThrowOnError>({
|
return (options.client ?? this._client).post<SessionSummarizeResponses, unknown, ThrowOnError>({
|
||||||
url: '/session/{id}/summarize',
|
url: "/session/{id}/summarize",
|
||||||
...options,
|
...options,
|
||||||
headers: {
|
headers: {
|
||||||
'Content-Type': 'application/json',
|
"Content-Type": "application/json",
|
||||||
...options.headers
|
...options.headers,
|
||||||
}
|
},
|
||||||
});
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -204,9 +275,9 @@ class Session extends _HeyApiClient {
|
|||||||
*/
|
*/
|
||||||
public messages<ThrowOnError extends boolean = false>(options: Options<SessionMessagesData, ThrowOnError>) {
|
public messages<ThrowOnError extends boolean = false>(options: Options<SessionMessagesData, ThrowOnError>) {
|
||||||
return (options.client ?? this._client).get<SessionMessagesResponses, unknown, ThrowOnError>({
|
return (options.client ?? this._client).get<SessionMessagesResponses, unknown, ThrowOnError>({
|
||||||
url: '/session/{id}/message',
|
url: "/session/{id}/message",
|
||||||
...options
|
...options,
|
||||||
});
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -214,13 +285,13 @@ class Session extends _HeyApiClient {
|
|||||||
*/
|
*/
|
||||||
public chat<ThrowOnError extends boolean = false>(options: Options<SessionChatData, ThrowOnError>) {
|
public chat<ThrowOnError extends boolean = false>(options: Options<SessionChatData, ThrowOnError>) {
|
||||||
return (options.client ?? this._client).post<SessionChatResponses, unknown, ThrowOnError>({
|
return (options.client ?? this._client).post<SessionChatResponses, unknown, ThrowOnError>({
|
||||||
url: '/session/{id}/message',
|
url: "/session/{id}/message",
|
||||||
...options,
|
...options,
|
||||||
headers: {
|
headers: {
|
||||||
'Content-Type': 'application/json',
|
"Content-Type": "application/json",
|
||||||
...options.headers
|
...options.headers,
|
||||||
}
|
},
|
||||||
});
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -228,9 +299,9 @@ class Session extends _HeyApiClient {
|
|||||||
*/
|
*/
|
||||||
public message<ThrowOnError extends boolean = false>(options: Options<SessionMessageData, ThrowOnError>) {
|
public message<ThrowOnError extends boolean = false>(options: Options<SessionMessageData, ThrowOnError>) {
|
||||||
return (options.client ?? this._client).get<SessionMessageResponses, unknown, ThrowOnError>({
|
return (options.client ?? this._client).get<SessionMessageResponses, unknown, ThrowOnError>({
|
||||||
url: '/session/{id}/message/{messageID}',
|
url: "/session/{id}/message/{messageID}",
|
||||||
...options
|
...options,
|
||||||
});
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -238,13 +309,13 @@ class Session extends _HeyApiClient {
|
|||||||
*/
|
*/
|
||||||
public revert<ThrowOnError extends boolean = false>(options: Options<SessionRevertData, ThrowOnError>) {
|
public revert<ThrowOnError extends boolean = false>(options: Options<SessionRevertData, ThrowOnError>) {
|
||||||
return (options.client ?? this._client).post<SessionRevertResponses, unknown, ThrowOnError>({
|
return (options.client ?? this._client).post<SessionRevertResponses, unknown, ThrowOnError>({
|
||||||
url: '/session/{id}/revert',
|
url: "/session/{id}/revert",
|
||||||
...options,
|
...options,
|
||||||
headers: {
|
headers: {
|
||||||
'Content-Type': 'application/json',
|
"Content-Type": "application/json",
|
||||||
...options.headers
|
...options.headers,
|
||||||
}
|
},
|
||||||
});
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -252,9 +323,9 @@ class Session extends _HeyApiClient {
|
|||||||
*/
|
*/
|
||||||
public unrevert<ThrowOnError extends boolean = false>(options: Options<SessionUnrevertData, ThrowOnError>) {
|
public unrevert<ThrowOnError extends boolean = false>(options: Options<SessionUnrevertData, ThrowOnError>) {
|
||||||
return (options.client ?? this._client).post<SessionUnrevertResponses, unknown, ThrowOnError>({
|
return (options.client ?? this._client).post<SessionUnrevertResponses, unknown, ThrowOnError>({
|
||||||
url: '/session/{id}/unrevert',
|
url: "/session/{id}/unrevert",
|
||||||
...options
|
...options,
|
||||||
});
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -264,9 +335,9 @@ class Find extends _HeyApiClient {
|
|||||||
*/
|
*/
|
||||||
public text<ThrowOnError extends boolean = false>(options: Options<FindTextData, ThrowOnError>) {
|
public text<ThrowOnError extends boolean = false>(options: Options<FindTextData, ThrowOnError>) {
|
||||||
return (options.client ?? this._client).get<FindTextResponses, unknown, ThrowOnError>({
|
return (options.client ?? this._client).get<FindTextResponses, unknown, ThrowOnError>({
|
||||||
url: '/find',
|
url: "/find",
|
||||||
...options
|
...options,
|
||||||
});
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -274,9 +345,9 @@ class Find extends _HeyApiClient {
|
|||||||
*/
|
*/
|
||||||
public files<ThrowOnError extends boolean = false>(options: Options<FindFilesData, ThrowOnError>) {
|
public files<ThrowOnError extends boolean = false>(options: Options<FindFilesData, ThrowOnError>) {
|
||||||
return (options.client ?? this._client).get<FindFilesResponses, unknown, ThrowOnError>({
|
return (options.client ?? this._client).get<FindFilesResponses, unknown, ThrowOnError>({
|
||||||
url: '/find/file',
|
url: "/find/file",
|
||||||
...options
|
...options,
|
||||||
});
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -284,9 +355,9 @@ class Find extends _HeyApiClient {
|
|||||||
*/
|
*/
|
||||||
public symbols<ThrowOnError extends boolean = false>(options: Options<FindSymbolsData, ThrowOnError>) {
|
public symbols<ThrowOnError extends boolean = false>(options: Options<FindSymbolsData, ThrowOnError>) {
|
||||||
return (options.client ?? this._client).get<FindSymbolsResponses, unknown, ThrowOnError>({
|
return (options.client ?? this._client).get<FindSymbolsResponses, unknown, ThrowOnError>({
|
||||||
url: '/find/symbol',
|
url: "/find/symbol",
|
||||||
...options
|
...options,
|
||||||
});
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -296,9 +367,9 @@ class File extends _HeyApiClient {
|
|||||||
*/
|
*/
|
||||||
public read<ThrowOnError extends boolean = false>(options: Options<FileReadData, ThrowOnError>) {
|
public read<ThrowOnError extends boolean = false>(options: Options<FileReadData, ThrowOnError>) {
|
||||||
return (options.client ?? this._client).get<FileReadResponses, unknown, ThrowOnError>({
|
return (options.client ?? this._client).get<FileReadResponses, unknown, ThrowOnError>({
|
||||||
url: '/file',
|
url: "/file",
|
||||||
...options
|
...options,
|
||||||
});
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -306,9 +377,9 @@ class File extends _HeyApiClient {
|
|||||||
*/
|
*/
|
||||||
public status<ThrowOnError extends boolean = false>(options?: Options<FileStatusData, ThrowOnError>) {
|
public status<ThrowOnError extends boolean = false>(options?: Options<FileStatusData, ThrowOnError>) {
|
||||||
return (options?.client ?? this._client).get<FileStatusResponses, unknown, ThrowOnError>({
|
return (options?.client ?? this._client).get<FileStatusResponses, unknown, ThrowOnError>({
|
||||||
url: '/file/status',
|
url: "/file/status",
|
||||||
...options
|
...options,
|
||||||
});
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -318,13 +389,13 @@ class Tui extends _HeyApiClient {
|
|||||||
*/
|
*/
|
||||||
public appendPrompt<ThrowOnError extends boolean = false>(options?: Options<TuiAppendPromptData, ThrowOnError>) {
|
public appendPrompt<ThrowOnError extends boolean = false>(options?: Options<TuiAppendPromptData, ThrowOnError>) {
|
||||||
return (options?.client ?? this._client).post<TuiAppendPromptResponses, unknown, ThrowOnError>({
|
return (options?.client ?? this._client).post<TuiAppendPromptResponses, unknown, ThrowOnError>({
|
||||||
url: '/tui/append-prompt',
|
url: "/tui/append-prompt",
|
||||||
...options,
|
...options,
|
||||||
headers: {
|
headers: {
|
||||||
'Content-Type': 'application/json',
|
"Content-Type": "application/json",
|
||||||
...options?.headers
|
...options?.headers,
|
||||||
}
|
},
|
||||||
});
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -332,9 +403,9 @@ class Tui extends _HeyApiClient {
|
|||||||
*/
|
*/
|
||||||
public openHelp<ThrowOnError extends boolean = false>(options?: Options<TuiOpenHelpData, ThrowOnError>) {
|
public openHelp<ThrowOnError extends boolean = false>(options?: Options<TuiOpenHelpData, ThrowOnError>) {
|
||||||
return (options?.client ?? this._client).post<TuiOpenHelpResponses, unknown, ThrowOnError>({
|
return (options?.client ?? this._client).post<TuiOpenHelpResponses, unknown, ThrowOnError>({
|
||||||
url: '/tui/open-help',
|
url: "/tui/open-help",
|
||||||
...options
|
...options,
|
||||||
});
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -342,9 +413,9 @@ class Tui extends _HeyApiClient {
|
|||||||
*/
|
*/
|
||||||
public openSessions<ThrowOnError extends boolean = false>(options?: Options<TuiOpenSessionsData, ThrowOnError>) {
|
public openSessions<ThrowOnError extends boolean = false>(options?: Options<TuiOpenSessionsData, ThrowOnError>) {
|
||||||
return (options?.client ?? this._client).post<TuiOpenSessionsResponses, unknown, ThrowOnError>({
|
return (options?.client ?? this._client).post<TuiOpenSessionsResponses, unknown, ThrowOnError>({
|
||||||
url: '/tui/open-sessions',
|
url: "/tui/open-sessions",
|
||||||
...options
|
...options,
|
||||||
});
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -352,9 +423,9 @@ class Tui extends _HeyApiClient {
|
|||||||
*/
|
*/
|
||||||
public openThemes<ThrowOnError extends boolean = false>(options?: Options<TuiOpenThemesData, ThrowOnError>) {
|
public openThemes<ThrowOnError extends boolean = false>(options?: Options<TuiOpenThemesData, ThrowOnError>) {
|
||||||
return (options?.client ?? this._client).post<TuiOpenThemesResponses, unknown, ThrowOnError>({
|
return (options?.client ?? this._client).post<TuiOpenThemesResponses, unknown, ThrowOnError>({
|
||||||
url: '/tui/open-themes',
|
url: "/tui/open-themes",
|
||||||
...options
|
...options,
|
||||||
});
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -362,9 +433,9 @@ class Tui extends _HeyApiClient {
|
|||||||
*/
|
*/
|
||||||
public openModels<ThrowOnError extends boolean = false>(options?: Options<TuiOpenModelsData, ThrowOnError>) {
|
public openModels<ThrowOnError extends boolean = false>(options?: Options<TuiOpenModelsData, ThrowOnError>) {
|
||||||
return (options?.client ?? this._client).post<TuiOpenModelsResponses, unknown, ThrowOnError>({
|
return (options?.client ?? this._client).post<TuiOpenModelsResponses, unknown, ThrowOnError>({
|
||||||
url: '/tui/open-models',
|
url: "/tui/open-models",
|
||||||
...options
|
...options,
|
||||||
});
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -372,9 +443,9 @@ class Tui extends _HeyApiClient {
|
|||||||
*/
|
*/
|
||||||
public submitPrompt<ThrowOnError extends boolean = false>(options?: Options<TuiSubmitPromptData, ThrowOnError>) {
|
public submitPrompt<ThrowOnError extends boolean = false>(options?: Options<TuiSubmitPromptData, ThrowOnError>) {
|
||||||
return (options?.client ?? this._client).post<TuiSubmitPromptResponses, unknown, ThrowOnError>({
|
return (options?.client ?? this._client).post<TuiSubmitPromptResponses, unknown, ThrowOnError>({
|
||||||
url: '/tui/submit-prompt',
|
url: "/tui/submit-prompt",
|
||||||
...options
|
...options,
|
||||||
});
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -382,9 +453,9 @@ class Tui extends _HeyApiClient {
|
|||||||
*/
|
*/
|
||||||
public clearPrompt<ThrowOnError extends boolean = false>(options?: Options<TuiClearPromptData, ThrowOnError>) {
|
public clearPrompt<ThrowOnError extends boolean = false>(options?: Options<TuiClearPromptData, ThrowOnError>) {
|
||||||
return (options?.client ?? this._client).post<TuiClearPromptResponses, unknown, ThrowOnError>({
|
return (options?.client ?? this._client).post<TuiClearPromptResponses, unknown, ThrowOnError>({
|
||||||
url: '/tui/clear-prompt',
|
url: "/tui/clear-prompt",
|
||||||
...options
|
...options,
|
||||||
});
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -392,13 +463,13 @@ class Tui extends _HeyApiClient {
|
|||||||
*/
|
*/
|
||||||
public executeCommand<ThrowOnError extends boolean = false>(options?: Options<TuiExecuteCommandData, ThrowOnError>) {
|
public executeCommand<ThrowOnError extends boolean = false>(options?: Options<TuiExecuteCommandData, ThrowOnError>) {
|
||||||
return (options?.client ?? this._client).post<TuiExecuteCommandResponses, unknown, ThrowOnError>({
|
return (options?.client ?? this._client).post<TuiExecuteCommandResponses, unknown, ThrowOnError>({
|
||||||
url: '/tui/execute-command',
|
url: "/tui/execute-command",
|
||||||
...options,
|
...options,
|
||||||
headers: {
|
headers: {
|
||||||
'Content-Type': 'application/json',
|
"Content-Type": "application/json",
|
||||||
...options?.headers
|
...options?.headers,
|
||||||
}
|
},
|
||||||
});
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -406,21 +477,27 @@ export class OpencodeClient extends _HeyApiClient {
|
|||||||
/**
|
/**
|
||||||
* Respond to a permission request
|
* Respond to a permission request
|
||||||
*/
|
*/
|
||||||
public postSessionByIdPermissionsByPermissionId<ThrowOnError extends boolean = false>(options: Options<PostSessionByIdPermissionsByPermissionIdData, ThrowOnError>) {
|
public postSessionByIdPermissionsByPermissionId<ThrowOnError extends boolean = false>(
|
||||||
return (options.client ?? this._client).post<PostSessionByIdPermissionsByPermissionIdResponses, unknown, ThrowOnError>({
|
options: Options<PostSessionByIdPermissionsByPermissionIdData, ThrowOnError>,
|
||||||
url: '/session/{id}/permissions/{permissionID}',
|
) {
|
||||||
|
return (options.client ?? this._client).post<
|
||||||
|
PostSessionByIdPermissionsByPermissionIdResponses,
|
||||||
|
unknown,
|
||||||
|
ThrowOnError
|
||||||
|
>({
|
||||||
|
url: "/session/{id}/permissions/{permissionID}",
|
||||||
...options,
|
...options,
|
||||||
headers: {
|
headers: {
|
||||||
'Content-Type': 'application/json',
|
"Content-Type": "application/json",
|
||||||
...options.headers
|
...options.headers,
|
||||||
|
},
|
||||||
|
})
|
||||||
}
|
}
|
||||||
});
|
event = new Event({ client: this._client })
|
||||||
}
|
app = new App({ client: this._client })
|
||||||
event = new Event({ client: this._client });
|
config = new Config({ client: this._client })
|
||||||
app = new App({ client: this._client });
|
session = new Session({ client: this._client })
|
||||||
config = new Config({ client: this._client });
|
find = new Find({ client: this._client })
|
||||||
session = new Session({ client: this._client });
|
file = new File({ client: this._client })
|
||||||
find = new Find({ client: this._client });
|
tui = new Tui({ client: this._client })
|
||||||
file = new File({ client: this._client });
|
|
||||||
tui = new Tui({ client: this._client });
|
|
||||||
}
|
}
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -1,6 +1,7 @@
|
|||||||
import { createClient } from "./gen/client/client"
|
import { createClient } from "./gen/client/client"
|
||||||
import { type Config } from "./gen/client/types"
|
import { type Config } from "./gen/client/types"
|
||||||
import { OpencodeClient } from "./gen/sdk.gen"
|
import { OpencodeClient } from "./gen/sdk.gen"
|
||||||
|
export * from "./gen/types.gen"
|
||||||
|
|
||||||
export function createOpencodeClient(config?: Config) {
|
export function createOpencodeClient(config?: Config) {
|
||||||
const client = createClient(config)
|
const client = createClient(config)
|
||||||
|
|||||||
@@ -5,7 +5,12 @@
|
|||||||
"outDir": "dist",
|
"outDir": "dist",
|
||||||
"module": "preserve",
|
"module": "preserve",
|
||||||
"declaration": true,
|
"declaration": true,
|
||||||
"moduleResolution": "bundler"
|
"moduleResolution": "bundler",
|
||||||
|
"lib": [
|
||||||
|
"es2022",
|
||||||
|
"dom",
|
||||||
|
"dom.iterable"
|
||||||
|
]
|
||||||
},
|
},
|
||||||
"include": [
|
"include": [
|
||||||
"src"
|
"src"
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
{
|
{
|
||||||
"name": "@opencode/web",
|
"name": "@opencode/web",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"version": "0.0.1",
|
"version": "0.0.0-202508022246",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"dev": "astro dev",
|
"dev": "astro dev",
|
||||||
"dev:remote": "sst shell --stage=dev --target=Web astro dev",
|
"dev:remote": "sst shell --stage=dev --target=Web astro dev",
|
||||||
|
|||||||
@@ -11,18 +11,39 @@ if (!version) {
|
|||||||
}
|
}
|
||||||
process.env["OPENCODE_VERSION"] = version
|
process.env["OPENCODE_VERSION"] = version
|
||||||
|
|
||||||
await import(`../packages/opencode/script/publish.ts`)
|
const pkgjsons = await Array.fromAsync(
|
||||||
|
new Bun.Glob("**/package.json").scan({
|
||||||
|
absolute: true,
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
|
||||||
|
const tree = await $`git add . && git write-tree`.text().then((x) => x.trim())
|
||||||
|
for await (const file of new Bun.Glob("**/package.json").scan({
|
||||||
|
absolute: true,
|
||||||
|
})) {
|
||||||
|
let pkg = await Bun.file(file).text()
|
||||||
|
pkg = pkg.replaceAll(/"version": "[^"]+"/g, `"version": "${version}"`)
|
||||||
|
await Bun.file(file).write(pkg)
|
||||||
|
}
|
||||||
|
|
||||||
|
// await import(`../packages/opencode/script/publish.ts`)
|
||||||
await import(`../packages/sdk/js/script/publish.ts`)
|
await import(`../packages/sdk/js/script/publish.ts`)
|
||||||
|
await import(`../packages/plugin/script/publish.ts`)
|
||||||
// await import(`../packages/sdk/stainless/generate.ts`)
|
// await import(`../packages/sdk/stainless/generate.ts`)
|
||||||
|
|
||||||
if (!snapshot) {
|
if (!snapshot) {
|
||||||
await $`git commit -am "release: v${version}"`
|
await $`git commit -am "release: v${version}"`
|
||||||
await $`git tag v${version}`
|
await $`git tag v${version}`
|
||||||
await $`git push origin HEAD --tags`
|
await $`git push origin HEAD --tags --no-verify`
|
||||||
}
|
}
|
||||||
if (snapshot) {
|
if (snapshot) {
|
||||||
await $`git commit --allow-empty -m "Snapshot release v${version}"`
|
await $`git commit --allow-empty -m "Snapshot release v${version}"`
|
||||||
await $`git tag v${version}`
|
await $`git tag v${version}`
|
||||||
await $`git push origin v${version}`
|
await $`git push origin v${version} --no-verify`
|
||||||
await $`git reset --soft HEAD~1`
|
await $`git reset --soft HEAD~1`
|
||||||
|
for await (const file of new Bun.Glob("**/package.json").scan({
|
||||||
|
absolute: true,
|
||||||
|
})) {
|
||||||
|
$`await git checkout ${tree} ${file}`
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
"name": "opencode",
|
"name": "opencode",
|
||||||
"displayName": "opencode",
|
"displayName": "opencode",
|
||||||
"description": "opencode for VS Code",
|
"description": "opencode for VS Code",
|
||||||
"version": "0.0.0",
|
"version": "0.0.0-202508022246",
|
||||||
"publisher": "sst-dev",
|
"publisher": "sst-dev",
|
||||||
"repository": {
|
"repository": {
|
||||||
"type": "git",
|
"type": "git",
|
||||||
|
|||||||
Reference in New Issue
Block a user