mirror of
https://github.com/sst/opencode.git
synced 2025-08-31 18:27:22 +00:00
ci: stuff
This commit is contained in:
parent
d47bb96784
commit
732b67f8ce
13 changed files with 161 additions and 471 deletions
|
@ -1,8 +1,8 @@
|
|||
export * from "./gen/types.gen.js"
|
||||
export { type Config as OpencodeClientConfig, OpencodeClient }
|
||||
|
||||
import { createClient } from "./gen/client/client.gen.js"
|
||||
import { type Config } from "./gen/client/types.gen.js"
|
||||
import { createClient } from "./gen/client/client.js"
|
||||
import { type Config } from "./gen/client/types.js"
|
||||
import { OpencodeClient } from "./gen/sdk.gen.js"
|
||||
|
||||
export function createOpencodeClient(config?: Config) {
|
||||
|
|
|
@ -1,7 +1,4 @@
|
|||
// This file is auto-generated by @hey-api/openapi-ts
|
||||
|
||||
import { createSseClient } from "../core/serverSentEvents.gen.js"
|
||||
import type { Client, Config, RequestOptions, ResolvedRequestOptions } from "./types.gen.js"
|
||||
import type { Client, Config, RequestOptions } from "./types.js"
|
||||
import {
|
||||
buildUrl,
|
||||
createConfig,
|
||||
|
@ -10,7 +7,7 @@ import {
|
|||
mergeConfigs,
|
||||
mergeHeaders,
|
||||
setAuthParams,
|
||||
} from "./utils.gen.js"
|
||||
} from "./utils.js"
|
||||
|
||||
type ReqInit = Omit<RequestInit, "body" | "headers"> & {
|
||||
body?: any
|
||||
|
@ -27,15 +24,14 @@ export const createClient = (config: Config = {}): Client => {
|
|||
return getConfig()
|
||||
}
|
||||
|
||||
const interceptors = createInterceptors<Request, Response, unknown, ResolvedRequestOptions>()
|
||||
const interceptors = createInterceptors<Request, Response, unknown, RequestOptions>()
|
||||
|
||||
const beforeRequest = async (options: RequestOptions) => {
|
||||
const request: Client["request"] = async (options) => {
|
||||
const opts = {
|
||||
..._config,
|
||||
...options,
|
||||
fetch: options.fetch ?? _config.fetch ?? globalThis.fetch,
|
||||
headers: mergeHeaders(_config.headers, options.headers),
|
||||
serializedBody: undefined,
|
||||
}
|
||||
|
||||
if (opts.security) {
|
||||
|
@ -50,26 +46,18 @@ export const createClient = (config: Config = {}): Client => {
|
|||
}
|
||||
|
||||
if (opts.body && opts.bodySerializer) {
|
||||
opts.serializedBody = opts.bodySerializer(opts.body)
|
||||
opts.body = opts.bodySerializer(opts.body)
|
||||
}
|
||||
|
||||
// remove Content-Type header if body is empty to avoid sending invalid requests
|
||||
if (opts.serializedBody === undefined || opts.serializedBody === "") {
|
||||
if (opts.body === undefined || opts.body === "") {
|
||||
opts.headers.delete("Content-Type")
|
||||
}
|
||||
|
||||
const url = buildUrl(opts)
|
||||
|
||||
return { opts, url }
|
||||
}
|
||||
|
||||
const request: Client["request"] = async (options) => {
|
||||
// @ts-expect-error
|
||||
const { opts, url } = await beforeRequest(options)
|
||||
const requestInit: ReqInit = {
|
||||
redirect: "follow",
|
||||
...opts,
|
||||
body: opts.serializedBody,
|
||||
}
|
||||
|
||||
let request = new Request(url, requestInit)
|
||||
|
@ -178,35 +166,20 @@ export const createClient = (config: Config = {}): Client => {
|
|||
}
|
||||
}
|
||||
|
||||
const makeMethod = (method: Required<Config>["method"]) => {
|
||||
const fn = (options: RequestOptions) => request({ ...options, method })
|
||||
fn.sse = async (options: RequestOptions) => {
|
||||
const { opts, url } = await beforeRequest(options)
|
||||
return createSseClient({
|
||||
...opts,
|
||||
body: opts.body as BodyInit | null | undefined,
|
||||
headers: opts.headers as unknown as Record<string, string>,
|
||||
method,
|
||||
url,
|
||||
})
|
||||
}
|
||||
return fn
|
||||
}
|
||||
|
||||
return {
|
||||
buildUrl,
|
||||
connect: makeMethod("CONNECT"),
|
||||
delete: makeMethod("DELETE"),
|
||||
get: makeMethod("GET"),
|
||||
connect: (options) => request({ ...options, method: "CONNECT" }),
|
||||
delete: (options) => request({ ...options, method: "DELETE" }),
|
||||
get: (options) => request({ ...options, method: "GET" }),
|
||||
getConfig,
|
||||
head: makeMethod("HEAD"),
|
||||
head: (options) => request({ ...options, method: "HEAD" }),
|
||||
interceptors,
|
||||
options: makeMethod("OPTIONS"),
|
||||
patch: makeMethod("PATCH"),
|
||||
post: makeMethod("POST"),
|
||||
put: makeMethod("PUT"),
|
||||
options: (options) => request({ ...options, method: "OPTIONS" }),
|
||||
patch: (options) => request({ ...options, method: "PATCH" }),
|
||||
post: (options) => request({ ...options, method: "POST" }),
|
||||
put: (options) => request({ ...options, method: "PUT" }),
|
||||
request,
|
||||
setConfig,
|
||||
trace: makeMethod("TRACE"),
|
||||
} as Client
|
||||
trace: (options) => request({ ...options, method: "TRACE" }),
|
||||
}
|
||||
}
|
|
@ -1,14 +1,8 @@
|
|||
// This file is auto-generated by @hey-api/openapi-ts
|
||||
|
||||
export type { Auth } from "../core/auth.gen.js"
|
||||
export type { QuerySerializerOptions } from "../core/bodySerializer.gen.js"
|
||||
export {
|
||||
formDataBodySerializer,
|
||||
jsonBodySerializer,
|
||||
urlSearchParamsBodySerializer,
|
||||
} from "../core/bodySerializer.gen.js"
|
||||
export { buildClientParams } from "../core/params.gen.js"
|
||||
export { createClient } from "./client.gen.js"
|
||||
export type { Auth } from "../core/auth.js"
|
||||
export type { QuerySerializerOptions } from "../core/bodySerializer.js"
|
||||
export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer } from "../core/bodySerializer.js"
|
||||
export { buildClientParams } from "../core/params.js"
|
||||
export { createClient } from "./client.js"
|
||||
export type {
|
||||
Client,
|
||||
ClientOptions,
|
||||
|
@ -18,8 +12,7 @@ export type {
|
|||
OptionsLegacyParser,
|
||||
RequestOptions,
|
||||
RequestResult,
|
||||
ResolvedRequestOptions,
|
||||
ResponseStyle,
|
||||
TDataShape,
|
||||
} from "./types.gen.js"
|
||||
export { createConfig, mergeHeaders } from "./utils.gen.js"
|
||||
} from "./types.js"
|
||||
export { createConfig, mergeHeaders } from "./utils.js"
|
||||
|
|
|
@ -1,9 +1,6 @@
|
|||
// This file is auto-generated by @hey-api/openapi-ts
|
||||
|
||||
import type { Auth } from "../core/auth.gen.js"
|
||||
import type { ServerSentEventsOptions, ServerSentEventsResult } from "../core/serverSentEvents.gen.js"
|
||||
import type { Client as CoreClient, Config as CoreConfig } from "../core/types.gen.js"
|
||||
import type { Middleware } from "./utils.gen.js"
|
||||
import type { Auth } from "../core/auth.js"
|
||||
import type { Client as CoreClient, Config as CoreConfig } from "../core/types.js"
|
||||
import type { Middleware } from "./utils.js"
|
||||
|
||||
export type ResponseStyle = "data" | "fields"
|
||||
|
||||
|
@ -52,18 +49,13 @@ export interface Config<T extends ClientOptions = ClientOptions>
|
|||
}
|
||||
|
||||
export interface RequestOptions<
|
||||
TData = unknown,
|
||||
TResponseStyle extends ResponseStyle = "fields",
|
||||
ThrowOnError extends boolean = boolean,
|
||||
Url extends string = string,
|
||||
> extends Config<{
|
||||
responseStyle: TResponseStyle
|
||||
throwOnError: ThrowOnError
|
||||
}>,
|
||||
Pick<
|
||||
ServerSentEventsOptions<TData>,
|
||||
"onSseError" | "onSseEvent" | "sseDefaultRetryDelay" | "sseMaxRetryAttempts" | "sseMaxRetryDelay"
|
||||
> {
|
||||
responseStyle: TResponseStyle
|
||||
throwOnError: ThrowOnError
|
||||
}> {
|
||||
/**
|
||||
* Any body that you want to add to your request.
|
||||
*
|
||||
|
@ -79,14 +71,6 @@ export interface RequestOptions<
|
|||
url: Url
|
||||
}
|
||||
|
||||
export interface ResolvedRequestOptions<
|
||||
TResponseStyle extends ResponseStyle = "fields",
|
||||
ThrowOnError extends boolean = boolean,
|
||||
Url extends string = string,
|
||||
> extends RequestOptions<unknown, TResponseStyle, ThrowOnError, Url> {
|
||||
serializedBody?: string
|
||||
}
|
||||
|
||||
export type RequestResult<
|
||||
TData = unknown,
|
||||
TError = unknown,
|
||||
|
@ -128,36 +112,23 @@ export interface ClientOptions {
|
|||
throwOnError?: boolean
|
||||
}
|
||||
|
||||
type MethodFnBase = <
|
||||
type MethodFn = <
|
||||
TData = unknown,
|
||||
TError = unknown,
|
||||
ThrowOnError extends boolean = false,
|
||||
TResponseStyle extends ResponseStyle = "fields",
|
||||
>(
|
||||
options: Omit<RequestOptions<TData, TResponseStyle, ThrowOnError>, "method">,
|
||||
options: Omit<RequestOptions<TResponseStyle, ThrowOnError>, "method">,
|
||||
) => RequestResult<TData, TError, ThrowOnError, TResponseStyle>
|
||||
|
||||
type MethodFnServerSentEvents = <
|
||||
TData = unknown,
|
||||
TError = unknown,
|
||||
ThrowOnError extends boolean = false,
|
||||
TResponseStyle extends ResponseStyle = "fields",
|
||||
>(
|
||||
options: Omit<RequestOptions<TData, TResponseStyle, ThrowOnError>, "method">,
|
||||
) => Promise<ServerSentEventsResult<TData, TError>>
|
||||
|
||||
type MethodFn = MethodFnBase & {
|
||||
sse: MethodFnServerSentEvents
|
||||
}
|
||||
|
||||
type RequestFn = <
|
||||
TData = unknown,
|
||||
TError = unknown,
|
||||
ThrowOnError extends boolean = false,
|
||||
TResponseStyle extends ResponseStyle = "fields",
|
||||
>(
|
||||
options: Omit<RequestOptions<TData, TResponseStyle, ThrowOnError>, "method"> &
|
||||
Pick<Required<RequestOptions<TData, TResponseStyle, ThrowOnError>>, "method">,
|
||||
options: Omit<RequestOptions<TResponseStyle, ThrowOnError>, "method"> &
|
||||
Pick<Required<RequestOptions<TResponseStyle, ThrowOnError>>, "method">,
|
||||
) => RequestResult<TData, TError, ThrowOnError, TResponseStyle>
|
||||
|
||||
type BuildUrlFn = <
|
||||
|
@ -172,7 +143,7 @@ type BuildUrlFn = <
|
|||
) => string
|
||||
|
||||
export type Client = CoreClient<RequestFn, Config, MethodFn, BuildUrlFn> & {
|
||||
interceptors: Middleware<Request, Response, unknown, ResolvedRequestOptions>
|
||||
interceptors: Middleware<Request, Response, unknown, RequestOptions>
|
||||
}
|
||||
|
||||
/**
|
||||
|
@ -200,10 +171,8 @@ type OmitKeys<T, K> = Pick<T, Exclude<keyof T, K>>
|
|||
export type Options<
|
||||
TData extends TDataShape = TDataShape,
|
||||
ThrowOnError extends boolean = boolean,
|
||||
TResponse = unknown,
|
||||
TResponseStyle extends ResponseStyle = "fields",
|
||||
> = OmitKeys<RequestOptions<TResponse, TResponseStyle, ThrowOnError>, "body" | "path" | "query" | "url"> &
|
||||
Omit<TData, "url">
|
||||
> = OmitKeys<RequestOptions<TResponseStyle, ThrowOnError>, "body" | "path" | "query" | "url"> & Omit<TData, "url">
|
||||
|
||||
export type OptionsLegacyParser<
|
||||
TData = unknown,
|
||||
|
@ -211,12 +180,12 @@ export type OptionsLegacyParser<
|
|||
TResponseStyle extends ResponseStyle = "fields",
|
||||
> = TData extends { body?: any }
|
||||
? TData extends { headers?: any }
|
||||
? OmitKeys<RequestOptions<unknown, TResponseStyle, ThrowOnError>, "body" | "headers" | "url"> & TData
|
||||
: OmitKeys<RequestOptions<unknown, TResponseStyle, ThrowOnError>, "body" | "url"> &
|
||||
? OmitKeys<RequestOptions<TResponseStyle, ThrowOnError>, "body" | "headers" | "url"> & TData
|
||||
: OmitKeys<RequestOptions<TResponseStyle, ThrowOnError>, "body" | "url"> &
|
||||
TData &
|
||||
Pick<RequestOptions<unknown, TResponseStyle, ThrowOnError>, "headers">
|
||||
Pick<RequestOptions<TResponseStyle, ThrowOnError>, "headers">
|
||||
: TData extends { headers?: any }
|
||||
? OmitKeys<RequestOptions<unknown, TResponseStyle, ThrowOnError>, "headers" | "url"> &
|
||||
? OmitKeys<RequestOptions<TResponseStyle, ThrowOnError>, "headers" | "url"> &
|
||||
TData &
|
||||
Pick<RequestOptions<unknown, TResponseStyle, ThrowOnError>, "body">
|
||||
: OmitKeys<RequestOptions<unknown, TResponseStyle, ThrowOnError>, "url"> & TData
|
||||
Pick<RequestOptions<TResponseStyle, ThrowOnError>, "body">
|
||||
: OmitKeys<RequestOptions<TResponseStyle, ThrowOnError>, "url"> & TData
|
|
@ -1,11 +1,84 @@
|
|||
// This file is auto-generated by @hey-api/openapi-ts
|
||||
import { getAuthToken } from "../core/auth.js"
|
||||
import type { QuerySerializer, QuerySerializerOptions } from "../core/bodySerializer.js"
|
||||
import { jsonBodySerializer } from "../core/bodySerializer.js"
|
||||
import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam } from "../core/pathSerializer.js"
|
||||
import type { Client, ClientOptions, Config, RequestOptions } from "./types.js"
|
||||
|
||||
import { getAuthToken } from "../core/auth.gen.js"
|
||||
import type { QuerySerializerOptions } from "../core/bodySerializer.gen.js"
|
||||
import { jsonBodySerializer } from "../core/bodySerializer.gen.js"
|
||||
import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam } from "../core/pathSerializer.gen.js"
|
||||
import { getUrl } from "../core/utils.gen.js"
|
||||
import type { Client, ClientOptions, Config, RequestOptions } from "./types.gen.js"
|
||||
interface PathSerializer {
|
||||
path: Record<string, unknown>
|
||||
url: string
|
||||
}
|
||||
|
||||
const PATH_PARAM_RE = /\{[^{}]+\}/g
|
||||
|
||||
type ArrayStyle = "form" | "spaceDelimited" | "pipeDelimited"
|
||||
type MatrixStyle = "label" | "matrix" | "simple"
|
||||
type ArraySeparatorStyle = ArrayStyle | MatrixStyle
|
||||
|
||||
const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => {
|
||||
let url = _url
|
||||
const matches = _url.match(PATH_PARAM_RE)
|
||||
if (matches) {
|
||||
for (const match of matches) {
|
||||
let explode = false
|
||||
let name = match.substring(1, match.length - 1)
|
||||
let style: ArraySeparatorStyle = "simple"
|
||||
|
||||
if (name.endsWith("*")) {
|
||||
explode = true
|
||||
name = name.substring(0, name.length - 1)
|
||||
}
|
||||
|
||||
if (name.startsWith(".")) {
|
||||
name = name.substring(1)
|
||||
style = "label"
|
||||
} else if (name.startsWith(";")) {
|
||||
name = name.substring(1)
|
||||
style = "matrix"
|
||||
}
|
||||
|
||||
const value = path[name]
|
||||
|
||||
if (value === undefined || value === null) {
|
||||
continue
|
||||
}
|
||||
|
||||
if (Array.isArray(value)) {
|
||||
url = url.replace(match, serializeArrayParam({ explode, name, style, value }))
|
||||
continue
|
||||
}
|
||||
|
||||
if (typeof value === "object") {
|
||||
url = url.replace(
|
||||
match,
|
||||
serializeObjectParam({
|
||||
explode,
|
||||
name,
|
||||
style,
|
||||
value: value as Record<string, unknown>,
|
||||
valueOnly: true,
|
||||
}),
|
||||
)
|
||||
continue
|
||||
}
|
||||
|
||||
if (style === "matrix") {
|
||||
url = url.replace(
|
||||
match,
|
||||
`;${serializePrimitiveParam({
|
||||
name,
|
||||
value: value as string,
|
||||
})}`,
|
||||
)
|
||||
continue
|
||||
}
|
||||
|
||||
const replaceValue = encodeURIComponent(style === "label" ? `.${value as string}` : (value as string))
|
||||
url = url.replace(match, replaceValue)
|
||||
}
|
||||
}
|
||||
return url
|
||||
}
|
||||
|
||||
export const createQuerySerializer = <T = unknown>({ allowReserved, array, object }: QuerySerializerOptions = {}) => {
|
||||
const querySerializer = (queryParams: T) => {
|
||||
|
@ -88,21 +161,6 @@ export const getParseAs = (contentType: string | null): Exclude<Config["parseAs"
|
|||
return
|
||||
}
|
||||
|
||||
const checkForExistence = (
|
||||
options: Pick<RequestOptions, "auth" | "query"> & {
|
||||
headers: Headers
|
||||
},
|
||||
name?: string,
|
||||
): boolean => {
|
||||
if (!name) {
|
||||
return false
|
||||
}
|
||||
if (options.headers.has(name) || options.query?.[name] || options.headers.get("Cookie")?.includes(`${name}=`)) {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
export const setAuthParams = async ({
|
||||
security,
|
||||
...options
|
||||
|
@ -111,10 +169,6 @@ export const setAuthParams = async ({
|
|||
headers: Headers
|
||||
}) => {
|
||||
for (const auth of security) {
|
||||
if (checkForExistence(options, auth.name)) {
|
||||
continue
|
||||
}
|
||||
|
||||
const token = await getAuthToken(auth, options.auth)
|
||||
|
||||
if (!token) {
|
||||
|
@ -138,11 +192,13 @@ export const setAuthParams = async ({
|
|||
options.headers.set(name, token)
|
||||
break
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
export const buildUrl: Client["buildUrl"] = (options) =>
|
||||
getUrl({
|
||||
export const buildUrl: Client["buildUrl"] = (options) => {
|
||||
const url = getUrl({
|
||||
baseUrl: options.baseUrl as string,
|
||||
path: options.path,
|
||||
query: options.query,
|
||||
|
@ -152,6 +208,36 @@ export const buildUrl: Client["buildUrl"] = (options) =>
|
|||
: createQuerySerializer(options.querySerializer),
|
||||
url: options.url,
|
||||
})
|
||||
return url
|
||||
}
|
||||
|
||||
export const getUrl = ({
|
||||
baseUrl,
|
||||
path,
|
||||
query,
|
||||
querySerializer,
|
||||
url: _url,
|
||||
}: {
|
||||
baseUrl?: string
|
||||
path?: Record<string, unknown>
|
||||
query?: Record<string, unknown>
|
||||
querySerializer: QuerySerializer
|
||||
url: string
|
||||
}) => {
|
||||
const pathUrl = _url.startsWith("/") ? _url : `/${_url}`
|
||||
let url = (baseUrl ?? "") + pathUrl
|
||||
if (path) {
|
||||
url = defaultPathSerializer({ path, url })
|
||||
}
|
||||
let search = query ? querySerializer(query) : ""
|
||||
if (search.startsWith("?")) {
|
||||
search = search.substring(1)
|
||||
}
|
||||
if (search) {
|
||||
url += `?${search}`
|
||||
}
|
||||
return url
|
||||
}
|
||||
|
||||
export const mergeConfigs = (a: Config, b: Config): Config => {
|
||||
const config = { ...a, ...b }
|
|
@ -1,5 +1,3 @@
|
|||
// This file is auto-generated by @hey-api/openapi-ts
|
||||
|
||||
export type AuthToken = string | undefined
|
||||
|
||||
export interface Auth {
|
|
@ -1,6 +1,4 @@
|
|||
// This file is auto-generated by @hey-api/openapi-ts
|
||||
|
||||
import type { ArrayStyle, ObjectStyle, SerializerOptions } from "./pathSerializer.gen.js"
|
||||
import type { ArrayStyle, ObjectStyle, SerializerOptions } from "./pathSerializer.js"
|
||||
|
||||
export type QuerySerializer = (query: Record<string, unknown>) => string
|
||||
|
||||
|
@ -15,8 +13,6 @@ export interface QuerySerializerOptions {
|
|||
const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => {
|
||||
if (typeof value === "string" || value instanceof Blob) {
|
||||
data.append(key, value)
|
||||
} else if (value instanceof Date) {
|
||||
data.append(key, value.toISOString())
|
||||
} else {
|
||||
data.append(key, JSON.stringify(value))
|
||||
}
|
|
@ -1,5 +1,3 @@
|
|||
// This file is auto-generated by @hey-api/openapi-ts
|
||||
|
||||
type Slot = "body" | "headers" | "path" | "query"
|
||||
|
||||
export type Field =
|
|
@ -1,5 +1,3 @@
|
|||
// This file is auto-generated by @hey-api/openapi-ts
|
||||
|
||||
interface SerializeOptions<T> extends SerializePrimitiveOptions, SerializerOptions<T> {}
|
||||
|
||||
interface SerializePrimitiveOptions {
|
|
@ -1,210 +0,0 @@
|
|||
// This file is auto-generated by @hey-api/openapi-ts
|
||||
|
||||
import type { Config } from "./types.gen.js"
|
||||
|
||||
export type ServerSentEventsOptions<TData = unknown> = Omit<RequestInit, "method"> &
|
||||
Pick<Config, "method" | "responseTransformer" | "responseValidator"> & {
|
||||
/**
|
||||
* Callback invoked when a network or parsing error occurs during streaming.
|
||||
*
|
||||
* This option applies only if the endpoint returns a stream of events.
|
||||
*
|
||||
* @param error The error that occurred.
|
||||
*/
|
||||
onSseError?: (error: unknown) => void
|
||||
/**
|
||||
* Callback invoked when an event is streamed from the server.
|
||||
*
|
||||
* This option applies only if the endpoint returns a stream of events.
|
||||
*
|
||||
* @param event Event streamed from the server.
|
||||
* @returns Nothing (void).
|
||||
*/
|
||||
onSseEvent?: (event: StreamEvent<TData>) => void
|
||||
/**
|
||||
* Default retry delay in milliseconds.
|
||||
*
|
||||
* This option applies only if the endpoint returns a stream of events.
|
||||
*
|
||||
* @default 3000
|
||||
*/
|
||||
sseDefaultRetryDelay?: number
|
||||
/**
|
||||
* Maximum number of retry attempts before giving up.
|
||||
*/
|
||||
sseMaxRetryAttempts?: number
|
||||
/**
|
||||
* Maximum retry delay in milliseconds.
|
||||
*
|
||||
* Applies only when exponential backoff is used.
|
||||
*
|
||||
* This option applies only if the endpoint returns a stream of events.
|
||||
*
|
||||
* @default 30000
|
||||
*/
|
||||
sseMaxRetryDelay?: number
|
||||
/**
|
||||
* Optional sleep function for retry backoff.
|
||||
*
|
||||
* Defaults to using `setTimeout`.
|
||||
*/
|
||||
sseSleepFn?: (ms: number) => Promise<void>
|
||||
url: string
|
||||
}
|
||||
|
||||
export interface StreamEvent<TData = unknown> {
|
||||
data: TData
|
||||
event?: string
|
||||
id?: string
|
||||
retry?: number
|
||||
}
|
||||
|
||||
export type ServerSentEventsResult<TData = unknown, TReturn = void, TNext = unknown> = {
|
||||
stream: AsyncGenerator<TData extends Record<string, unknown> ? TData[keyof TData] : TData, TReturn, TNext>
|
||||
}
|
||||
|
||||
export const createSseClient = <TData = unknown>({
|
||||
onSseError,
|
||||
onSseEvent,
|
||||
responseTransformer,
|
||||
responseValidator,
|
||||
sseDefaultRetryDelay,
|
||||
sseMaxRetryAttempts,
|
||||
sseMaxRetryDelay,
|
||||
sseSleepFn,
|
||||
url,
|
||||
...options
|
||||
}: ServerSentEventsOptions): ServerSentEventsResult<TData> => {
|
||||
let lastEventId: string | undefined
|
||||
|
||||
const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms)))
|
||||
|
||||
const createStream = async function* () {
|
||||
let retryDelay: number = sseDefaultRetryDelay ?? 3000
|
||||
let attempt = 0
|
||||
const signal = options.signal ?? new AbortController().signal
|
||||
|
||||
while (true) {
|
||||
if (signal.aborted) break
|
||||
|
||||
attempt++
|
||||
|
||||
const headers =
|
||||
options.headers instanceof Headers
|
||||
? options.headers
|
||||
: new Headers(options.headers as Record<string, string> | undefined)
|
||||
|
||||
if (lastEventId !== undefined) {
|
||||
headers.set("Last-Event-ID", lastEventId)
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await fetch(url, { ...options, headers, signal })
|
||||
|
||||
if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`)
|
||||
|
||||
if (!response.body) throw new Error("No body in SSE response")
|
||||
|
||||
const reader = response.body.pipeThrough(new TextDecoderStream()).getReader()
|
||||
|
||||
let buffer = ""
|
||||
|
||||
const abortHandler = () => {
|
||||
try {
|
||||
reader.cancel()
|
||||
} catch {
|
||||
// noop
|
||||
}
|
||||
}
|
||||
|
||||
signal.addEventListener("abort", abortHandler)
|
||||
|
||||
try {
|
||||
while (true) {
|
||||
const { done, value } = await reader.read()
|
||||
if (done) break
|
||||
buffer += value
|
||||
|
||||
const chunks = buffer.split("\n\n")
|
||||
buffer = chunks.pop() ?? ""
|
||||
|
||||
for (const chunk of chunks) {
|
||||
const lines = chunk.split("\n")
|
||||
const dataLines: Array<string> = []
|
||||
let eventName: string | undefined
|
||||
|
||||
for (const line of lines) {
|
||||
if (line.startsWith("data:")) {
|
||||
dataLines.push(line.replace(/^data:\s*/, ""))
|
||||
} else if (line.startsWith("event:")) {
|
||||
eventName = line.replace(/^event:\s*/, "")
|
||||
} else if (line.startsWith("id:")) {
|
||||
lastEventId = line.replace(/^id:\s*/, "")
|
||||
} else if (line.startsWith("retry:")) {
|
||||
const parsed = Number.parseInt(line.replace(/^retry:\s*/, ""), 10)
|
||||
if (!Number.isNaN(parsed)) {
|
||||
retryDelay = parsed
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let data: unknown
|
||||
let parsedJson = false
|
||||
|
||||
if (dataLines.length) {
|
||||
const rawData = dataLines.join("\n")
|
||||
try {
|
||||
data = JSON.parse(rawData)
|
||||
parsedJson = true
|
||||
} catch {
|
||||
data = rawData
|
||||
}
|
||||
}
|
||||
|
||||
if (parsedJson) {
|
||||
if (responseValidator) {
|
||||
await responseValidator(data)
|
||||
}
|
||||
|
||||
if (responseTransformer) {
|
||||
data = await responseTransformer(data)
|
||||
}
|
||||
}
|
||||
|
||||
onSseEvent?.({
|
||||
data,
|
||||
event: eventName,
|
||||
id: lastEventId,
|
||||
retry: retryDelay,
|
||||
})
|
||||
|
||||
if (dataLines.length) {
|
||||
yield data as any
|
||||
}
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
signal.removeEventListener("abort", abortHandler)
|
||||
reader.releaseLock()
|
||||
}
|
||||
|
||||
break // exit loop on normal completion
|
||||
} catch (error) {
|
||||
// connection failed or aborted; retry after delay
|
||||
onSseError?.(error)
|
||||
|
||||
if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) {
|
||||
break // stop after firing error
|
||||
}
|
||||
|
||||
// exponential backoff: double retry each attempt, cap at 30s
|
||||
const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000)
|
||||
await sleep(backoff)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const stream = createStream()
|
||||
|
||||
return { stream }
|
||||
}
|
|
@ -1,7 +1,5 @@
|
|||
// This file is auto-generated by @hey-api/openapi-ts
|
||||
|
||||
import type { Auth, AuthToken } from "./auth.gen.js"
|
||||
import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from "./bodySerializer.gen.js"
|
||||
import type { Auth, AuthToken } from "./auth.js"
|
||||
import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from "./bodySerializer.js"
|
||||
|
||||
export interface Client<RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never> {
|
||||
/**
|
|
@ -1,109 +0,0 @@
|
|||
// This file is auto-generated by @hey-api/openapi-ts
|
||||
|
||||
import type { QuerySerializer } from "./bodySerializer.gen.js"
|
||||
import {
|
||||
type ArraySeparatorStyle,
|
||||
serializeArrayParam,
|
||||
serializeObjectParam,
|
||||
serializePrimitiveParam,
|
||||
} from "./pathSerializer.gen.js"
|
||||
|
||||
export interface PathSerializer {
|
||||
path: Record<string, unknown>
|
||||
url: string
|
||||
}
|
||||
|
||||
export const PATH_PARAM_RE = /\{[^{}]+\}/g
|
||||
|
||||
export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => {
|
||||
let url = _url
|
||||
const matches = _url.match(PATH_PARAM_RE)
|
||||
if (matches) {
|
||||
for (const match of matches) {
|
||||
let explode = false
|
||||
let name = match.substring(1, match.length - 1)
|
||||
let style: ArraySeparatorStyle = "simple"
|
||||
|
||||
if (name.endsWith("*")) {
|
||||
explode = true
|
||||
name = name.substring(0, name.length - 1)
|
||||
}
|
||||
|
||||
if (name.startsWith(".")) {
|
||||
name = name.substring(1)
|
||||
style = "label"
|
||||
} else if (name.startsWith(";")) {
|
||||
name = name.substring(1)
|
||||
style = "matrix"
|
||||
}
|
||||
|
||||
const value = path[name]
|
||||
|
||||
if (value === undefined || value === null) {
|
||||
continue
|
||||
}
|
||||
|
||||
if (Array.isArray(value)) {
|
||||
url = url.replace(match, serializeArrayParam({ explode, name, style, value }))
|
||||
continue
|
||||
}
|
||||
|
||||
if (typeof value === "object") {
|
||||
url = url.replace(
|
||||
match,
|
||||
serializeObjectParam({
|
||||
explode,
|
||||
name,
|
||||
style,
|
||||
value: value as Record<string, unknown>,
|
||||
valueOnly: true,
|
||||
}),
|
||||
)
|
||||
continue
|
||||
}
|
||||
|
||||
if (style === "matrix") {
|
||||
url = url.replace(
|
||||
match,
|
||||
`;${serializePrimitiveParam({
|
||||
name,
|
||||
value: value as string,
|
||||
})}`,
|
||||
)
|
||||
continue
|
||||
}
|
||||
|
||||
const replaceValue = encodeURIComponent(style === "label" ? `.${value as string}` : (value as string))
|
||||
url = url.replace(match, replaceValue)
|
||||
}
|
||||
}
|
||||
return url
|
||||
}
|
||||
|
||||
export const getUrl = ({
|
||||
baseUrl,
|
||||
path,
|
||||
query,
|
||||
querySerializer,
|
||||
url: _url,
|
||||
}: {
|
||||
baseUrl?: string
|
||||
path?: Record<string, unknown>
|
||||
query?: Record<string, unknown>
|
||||
querySerializer: QuerySerializer
|
||||
url: string
|
||||
}) => {
|
||||
const pathUrl = _url.startsWith("/") ? _url : `/${_url}`
|
||||
let url = (baseUrl ?? "") + pathUrl
|
||||
if (path) {
|
||||
url = defaultPathSerializer({ path, url })
|
||||
}
|
||||
let search = query ? querySerializer(query) : ""
|
||||
if (search.startsWith("?")) {
|
||||
search = search.substring(1)
|
||||
}
|
||||
if (search) {
|
||||
url += `?${search}`
|
||||
}
|
||||
return url
|
||||
}
|
|
@ -123,7 +123,7 @@ class Event extends _HeyApiClient {
|
|||
* Get events
|
||||
*/
|
||||
public subscribe<ThrowOnError extends boolean = false>(options?: Options<EventSubscribeData, ThrowOnError>) {
|
||||
return (options?.client ?? this._client).get.sse<EventSubscribeResponses, unknown, ThrowOnError>({
|
||||
return (options?.client ?? this._client).get<EventSubscribeResponses, unknown, ThrowOnError>({
|
||||
url: "/event",
|
||||
...options,
|
||||
})
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue