diff --git a/dev/openapi-ts.config.ts b/dev/openapi-ts.config.ts index e391a6546..d3586b30d 100644 --- a/dev/openapi-ts.config.ts +++ b/dev/openapi-ts.config.ts @@ -107,11 +107,11 @@ export default defineConfig(() => { // indexFile: false, // lint: 'eslint', nameConflictResolver({ attempt, baseName }) { - console.log('resolving conflict for:', { attempt, baseName }); + // console.log('resolving conflict for:', { attempt, baseName }); return attempt === 0 ? baseName : `${baseName}_N${attempt + 1}`; }, path: path.resolve(__dirname, '.gen'), - preferExportAll: true, + // preferExportAll: true, resolveModuleName: (moduleName) => { if (moduleName === 'valibot') { return 'valibot'; @@ -146,6 +146,14 @@ export default defineConfig(() => { }, hooks: { events: { + // 'node:set:after': ({ node, plugin }) => { + // if (node) { + // console.log(`(${plugin.name}) set node:`, node.symbol); + // } + // }, + // 'node:set:before': ({ node, plugin }) => { + // console.log(`(${plugin.name}) setting node:`, node?.symbol?.id); + // }, // 'plugin:handler:after': ({ plugin }) => { // console.log(`(${plugin.name}): handler finished`); // }, @@ -171,12 +179,6 @@ export default defineConfig(() => { // ); // } }, - // 'symbol:setValue:after': ({ plugin, symbol }) => { - // console.log(`(${plugin.name}) set value:`, symbol.id); - // }, - // 'symbol:setValue:before': ({ plugin, symbol }) => { - // console.log(`(${plugin.name}) setting value:`, symbol.id); - // }, }, operations: { getKind() { diff --git a/docs/openapi-ts/configuration/output.md b/docs/openapi-ts/configuration/output.md index a47ace0e4..8c7627986 100644 --- a/docs/openapi-ts/configuration/output.md +++ b/docs/openapi-ts/configuration/output.md @@ -108,9 +108,9 @@ export default { ::: -## Import File Extension +## Module Extension -You can customize the extension used for imported TypeScript files. +You can customize the extension used for TypeScript modules. ::: code-group @@ -258,6 +258,33 @@ export default { You can also prevent your output from being linted by adding your output path to the linter's ignore file. +## Name Conflicts + +As your project grows, the chances of name conflicts increase. We use a simple conflict resolver that appends numeric suffixes to duplicate identifiers. If you prefer a different strategy, you can provide your own `nameConflictResolver` function. + +::: code-group + +```js [config] +export default { + input: 'hey-api/backend', // sign up at app.heyapi.dev + output: { + nameConflictResolver({ attempt, baseName }) { + // [!code ++] + return attempt === 0 ? baseName : `${baseName}_N${attempt + 1}`; // [!code ++] + }, // [!code ++] + path: 'src/client', + }, +}; +``` + +```ts [example] +export type ChatCompletion = string; + +export type ChatCompletion_N2 = number; +``` + +::: + ## TSConfig Path We use the [TSConfig file](https://www.typescriptlang.org/tsconfig/) to generate output matching your project's settings. By default, we attempt to find a TSConfig file starting from the location of the `@hey-api/openapi-ts` configuration file and traversing up. diff --git a/docs/openapi-ts/migrating.md b/docs/openapi-ts/migrating.md index 39953f135..063bfaf89 100644 --- a/docs/openapi-ts/migrating.md +++ b/docs/openapi-ts/migrating.md @@ -7,6 +7,28 @@ description: Migrating to @hey-api/openapi-ts. While we try to avoid breaking changes, sometimes it's unavoidable in order to offer you the latest features. This page lists changes that require updates to your code. If you run into a problem with migration, please [open an issue](https://github.com/hey-api/openapi-ts/issues). +## v0.89.0 + +### Prefer named exports + +This release changes the default for `index.ts` to prefer named exports. Named exports may lead to better IDE and bundler performance compared to asterisk (`*`) as your tooling doesn't have to inspect the underlying module to discover exports. + +While this change is merely cosmetic, you can set `output.preferExportAll` to `true` if you prefer to use the asterisk. + +```js +export default { + input: 'hey-api/backend', // sign up at app.heyapi.dev + output: { + path: 'src/client', + preferExportAll: true, // [!code ++] + }, +}; +``` + +### Removed `symbol:setValue:*` events + +These events have been removed in favor of `node:set:*` events. + ## v0.88.0 ### Removed `compiler` and `tsc` exports diff --git a/docs/openapi-ts/output.md b/docs/openapi-ts/output.md index a949e215b..cffd611a6 100644 --- a/docs/openapi-ts/output.md +++ b/docs/openapi-ts/output.md @@ -111,9 +111,5 @@ export default { }; ``` -::: warning -Re-exporting additional files from index file may result in broken output due to naming conflicts. -::: - diff --git a/packages/codegen-core/src/planner/planner.ts b/packages/codegen-core/src/planner/planner.ts index 25bfe34ba..ca0467166 100644 --- a/packages/codegen-core/src/planner/planner.ts +++ b/packages/codegen-core/src/planner/planner.ts @@ -384,10 +384,10 @@ export class Planner { const ok = kinds.every((kind) => canShareName(symbol.kind, kind)); if (ok) break; + const language = symbol.node?.language || symbol.file?.language; const resolver = - (symbol.node?.language - ? this.project.nameConflictResolvers[symbol.node.language] - : undefined) ?? this.project.defaultNameConflictResolver; + (language ? this.project.nameConflictResolvers[language] : undefined) ?? + this.project.defaultNameConflictResolver; const resolvedName = resolver({ attempt, baseName }); if (!resolvedName) { throw new Error(`Unresolvable name conflict: ${symbol.toString()}`); diff --git a/packages/openapi-ts-tests/sdks/__snapshots__/opencode/export-all/client.gen.ts b/packages/openapi-ts-tests/sdks/__snapshots__/opencode/export-all/client.gen.ts new file mode 100644 index 000000000..cab3c7019 --- /dev/null +++ b/packages/openapi-ts-tests/sdks/__snapshots__/opencode/export-all/client.gen.ts @@ -0,0 +1,16 @@ +// This file is auto-generated by @hey-api/openapi-ts + +import { type ClientOptions, type Config, createClient, createConfig } from './client'; +import type { ClientOptions as ClientOptions2 } from './types.gen'; + +/** + * The `createClientConfig()` function will be called on client initialization + * and the returned object will become the client's initial configuration. + * + * You may want to initialize your client this way instead of calling + * `setConfig()`. This is useful for example if you're using Next.js + * to ensure your client always has the correct values. + */ +export type CreateClientConfig = (override?: Config) => Config & T>; + +export const client = createClient(createConfig()); diff --git a/packages/openapi-ts-tests/sdks/__snapshots__/opencode/export-all/client/client.gen.ts b/packages/openapi-ts-tests/sdks/__snapshots__/opencode/export-all/client/client.gen.ts new file mode 100644 index 000000000..c2a5190c2 --- /dev/null +++ b/packages/openapi-ts-tests/sdks/__snapshots__/opencode/export-all/client/client.gen.ts @@ -0,0 +1,301 @@ +// This file is auto-generated by @hey-api/openapi-ts + +import { createSseClient } from '../core/serverSentEvents.gen'; +import type { HttpMethod } from '../core/types.gen'; +import { getValidRequestBody } from '../core/utils.gen'; +import type { + Client, + Config, + RequestOptions, + ResolvedRequestOptions, +} from './types.gen'; +import { + buildUrl, + createConfig, + createInterceptors, + getParseAs, + mergeConfigs, + mergeHeaders, + setAuthParams, +} from './utils.gen'; + +type ReqInit = Omit & { + body?: any; + headers: ReturnType; +}; + +export const createClient = (config: Config = {}): Client => { + let _config = mergeConfigs(createConfig(), config); + + const getConfig = (): Config => ({ ..._config }); + + const setConfig = (config: Config): Config => { + _config = mergeConfigs(_config, config); + return getConfig(); + }; + + const interceptors = createInterceptors< + Request, + Response, + unknown, + ResolvedRequestOptions + >(); + + const beforeRequest = async (options: RequestOptions) => { + const opts = { + ..._config, + ...options, + fetch: options.fetch ?? _config.fetch ?? globalThis.fetch, + headers: mergeHeaders(_config.headers, options.headers), + serializedBody: undefined, + }; + + if (opts.security) { + await setAuthParams({ + ...opts, + security: opts.security, + }); + } + + if (opts.requestValidator) { + await opts.requestValidator(opts); + } + + if (opts.body !== undefined && opts.bodySerializer) { + opts.serializedBody = opts.bodySerializer(opts.body); + } + + // remove Content-Type header if body is empty to avoid sending invalid requests + if (opts.body === undefined || opts.serializedBody === '') { + opts.headers.delete('Content-Type'); + } + + const url = buildUrl(opts); + + return { opts, url }; + }; + + const request: Client['request'] = async (options) => { + // @ts-expect-error + const { opts, url } = await beforeRequest(options); + const requestInit: ReqInit = { + redirect: 'follow', + ...opts, + body: getValidRequestBody(opts), + }; + + let request = new Request(url, requestInit); + + for (const fn of interceptors.request.fns) { + if (fn) { + request = await fn(request, opts); + } + } + + // fetch must be assigned here, otherwise it would throw the error: + // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation + const _fetch = opts.fetch!; + let response: Response; + + try { + response = await _fetch(request); + } catch (error) { + // Handle fetch exceptions (AbortError, network errors, etc.) + let finalError = error; + + for (const fn of interceptors.error.fns) { + if (fn) { + finalError = (await fn( + error, + undefined as any, + request, + opts, + )) as unknown; + } + } + + finalError = finalError || ({} as unknown); + + if (opts.throwOnError) { + throw finalError; + } + + // Return error response + return opts.responseStyle === 'data' + ? undefined + : { + error: finalError, + request, + response: undefined as any, + }; + } + + for (const fn of interceptors.response.fns) { + if (fn) { + response = await fn(response, request, opts); + } + } + + const result = { + request, + response, + }; + + if (response.ok) { + const parseAs = + (opts.parseAs === 'auto' + ? getParseAs(response.headers.get('Content-Type')) + : opts.parseAs) ?? 'json'; + + if ( + response.status === 204 || + response.headers.get('Content-Length') === '0' + ) { + let emptyData: any; + switch (parseAs) { + case 'arrayBuffer': + case 'blob': + case 'text': + emptyData = await response[parseAs](); + break; + case 'formData': + emptyData = new FormData(); + break; + case 'stream': + emptyData = response.body; + break; + case 'json': + default: + emptyData = {}; + break; + } + return opts.responseStyle === 'data' + ? emptyData + : { + data: emptyData, + ...result, + }; + } + + let data: any; + switch (parseAs) { + case 'arrayBuffer': + case 'blob': + case 'formData': + case 'json': + case 'text': + data = await response[parseAs](); + break; + case 'stream': + return opts.responseStyle === 'data' + ? response.body + : { + data: response.body, + ...result, + }; + } + + if (parseAs === 'json') { + if (opts.responseValidator) { + await opts.responseValidator(data); + } + + if (opts.responseTransformer) { + data = await opts.responseTransformer(data); + } + } + + return opts.responseStyle === 'data' + ? data + : { + data, + ...result, + }; + } + + const textError = await response.text(); + let jsonError: unknown; + + try { + jsonError = JSON.parse(textError); + } catch { + // noop + } + + const error = jsonError ?? textError; + let finalError = error; + + for (const fn of interceptors.error.fns) { + if (fn) { + finalError = (await fn(error, response, request, opts)) as string; + } + } + + finalError = finalError || ({} as string); + + if (opts.throwOnError) { + throw finalError; + } + + // TODO: we probably want to return error and improve types + return opts.responseStyle === 'data' + ? undefined + : { + error: finalError, + ...result, + }; + }; + + const makeMethodFn = + (method: Uppercase) => (options: RequestOptions) => + request({ ...options, method }); + + const makeSseFn = + (method: Uppercase) => 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, + method, + onRequest: async (url, init) => { + let request = new Request(url, init); + for (const fn of interceptors.request.fns) { + if (fn) { + request = await fn(request, opts); + } + } + return request; + }, + url, + }); + }; + + return { + buildUrl, + connect: makeMethodFn('CONNECT'), + delete: makeMethodFn('DELETE'), + get: makeMethodFn('GET'), + getConfig, + head: makeMethodFn('HEAD'), + interceptors, + options: makeMethodFn('OPTIONS'), + patch: makeMethodFn('PATCH'), + post: makeMethodFn('POST'), + put: makeMethodFn('PUT'), + request, + setConfig, + sse: { + connect: makeSseFn('CONNECT'), + delete: makeSseFn('DELETE'), + get: makeSseFn('GET'), + head: makeSseFn('HEAD'), + options: makeSseFn('OPTIONS'), + patch: makeSseFn('PATCH'), + post: makeSseFn('POST'), + put: makeSseFn('PUT'), + trace: makeSseFn('TRACE'), + }, + trace: makeMethodFn('TRACE'), + } as Client; +}; diff --git a/packages/openapi-ts-tests/sdks/__snapshots__/opencode/export-all/client/index.ts b/packages/openapi-ts-tests/sdks/__snapshots__/opencode/export-all/client/index.ts new file mode 100644 index 000000000..b295edeca --- /dev/null +++ b/packages/openapi-ts-tests/sdks/__snapshots__/opencode/export-all/client/index.ts @@ -0,0 +1,25 @@ +// This file is auto-generated by @hey-api/openapi-ts + +export type { Auth } from '../core/auth.gen'; +export type { QuerySerializerOptions } from '../core/bodySerializer.gen'; +export { + formDataBodySerializer, + jsonBodySerializer, + urlSearchParamsBodySerializer, +} from '../core/bodySerializer.gen'; +export { buildClientParams } from '../core/params.gen'; +export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen'; +export { createClient } from './client.gen'; +export type { + Client, + ClientOptions, + Config, + CreateClientConfig, + Options, + RequestOptions, + RequestResult, + ResolvedRequestOptions, + ResponseStyle, + TDataShape, +} from './types.gen'; +export { createConfig, mergeHeaders } from './utils.gen'; diff --git a/packages/openapi-ts-tests/sdks/__snapshots__/opencode/export-all/client/types.gen.ts b/packages/openapi-ts-tests/sdks/__snapshots__/opencode/export-all/client/types.gen.ts new file mode 100644 index 000000000..b4a499cc0 --- /dev/null +++ b/packages/openapi-ts-tests/sdks/__snapshots__/opencode/export-all/client/types.gen.ts @@ -0,0 +1,241 @@ +// This file is auto-generated by @hey-api/openapi-ts + +import type { Auth } from '../core/auth.gen'; +import type { + ServerSentEventsOptions, + ServerSentEventsResult, +} from '../core/serverSentEvents.gen'; +import type { + Client as CoreClient, + Config as CoreConfig, +} from '../core/types.gen'; +import type { Middleware } from './utils.gen'; + +export type ResponseStyle = 'data' | 'fields'; + +export interface Config + extends Omit, + CoreConfig { + /** + * Base URL for all requests made by this client. + */ + baseUrl?: T['baseUrl']; + /** + * Fetch API implementation. You can use this option to provide a custom + * fetch instance. + * + * @default globalThis.fetch + */ + fetch?: typeof fetch; + /** + * Please don't use the Fetch client for Next.js applications. The `next` + * options won't have any effect. + * + * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead. + */ + next?: never; + /** + * Return the response data parsed in a specified format. By default, `auto` + * will infer the appropriate method from the `Content-Type` response header. + * You can override this behavior with any of the {@link Body} methods. + * Select `stream` if you don't want to parse response data at all. + * + * @default 'auto' + */ + parseAs?: + | 'arrayBuffer' + | 'auto' + | 'blob' + | 'formData' + | 'json' + | 'stream' + | 'text'; + /** + * Should we return only data or multiple fields (data, error, response, etc.)? + * + * @default 'fields' + */ + responseStyle?: ResponseStyle; + /** + * Throw an error instead of returning it in the response? + * + * @default false + */ + throwOnError?: T['throwOnError']; +} + +export interface RequestOptions< + TData = unknown, + TResponseStyle extends ResponseStyle = 'fields', + ThrowOnError extends boolean = boolean, + Url extends string = string, +> extends Config<{ + responseStyle: TResponseStyle; + throwOnError: ThrowOnError; + }>, + Pick< + ServerSentEventsOptions, + | 'onSseError' + | 'onSseEvent' + | 'sseDefaultRetryDelay' + | 'sseMaxRetryAttempts' + | 'sseMaxRetryDelay' + > { + /** + * Any body that you want to add to your request. + * + * {@link https://developer.mozilla.org/docs/Web/API/fetch#body} + */ + body?: unknown; + path?: Record; + query?: Record; + /** + * Security mechanism(s) to use for the request. + */ + security?: ReadonlyArray; + url: Url; +} + +export interface ResolvedRequestOptions< + TResponseStyle extends ResponseStyle = 'fields', + ThrowOnError extends boolean = boolean, + Url extends string = string, +> extends RequestOptions { + serializedBody?: string; +} + +export type RequestResult< + TData = unknown, + TError = unknown, + ThrowOnError extends boolean = boolean, + TResponseStyle extends ResponseStyle = 'fields', +> = ThrowOnError extends true + ? Promise< + TResponseStyle extends 'data' + ? TData extends Record + ? TData[keyof TData] + : TData + : { + data: TData extends Record + ? TData[keyof TData] + : TData; + request: Request; + response: Response; + } + > + : Promise< + TResponseStyle extends 'data' + ? + | (TData extends Record + ? TData[keyof TData] + : TData) + | undefined + : ( + | { + data: TData extends Record + ? TData[keyof TData] + : TData; + error: undefined; + } + | { + data: undefined; + error: TError extends Record + ? TError[keyof TError] + : TError; + } + ) & { + request: Request; + response: Response; + } + >; + +export interface ClientOptions { + baseUrl?: string; + responseStyle?: ResponseStyle; + throwOnError?: boolean; +} + +type MethodFn = < + TData = unknown, + TError = unknown, + ThrowOnError extends boolean = false, + TResponseStyle extends ResponseStyle = 'fields', +>( + options: Omit, 'method'>, +) => RequestResult; + +type SseFn = < + TData = unknown, + TError = unknown, + ThrowOnError extends boolean = false, + TResponseStyle extends ResponseStyle = 'fields', +>( + options: Omit, 'method'>, +) => Promise>; + +type RequestFn = < + TData = unknown, + TError = unknown, + ThrowOnError extends boolean = false, + TResponseStyle extends ResponseStyle = 'fields', +>( + options: Omit, 'method'> & + Pick< + Required>, + 'method' + >, +) => RequestResult; + +type BuildUrlFn = < + TData extends { + body?: unknown; + path?: Record; + query?: Record; + url: string; + }, +>( + options: TData & Options, +) => string; + +export type Client = CoreClient< + RequestFn, + Config, + MethodFn, + BuildUrlFn, + SseFn +> & { + interceptors: Middleware; +}; + +/** + * The `createClientConfig()` function will be called on client initialization + * and the returned object will become the client's initial configuration. + * + * You may want to initialize your client this way instead of calling + * `setConfig()`. This is useful for example if you're using Next.js + * to ensure your client always has the correct values. + */ +export type CreateClientConfig = ( + override?: Config, +) => Config & T>; + +export interface TDataShape { + body?: unknown; + headers?: unknown; + path?: unknown; + query?: unknown; + url: string; +} + +type OmitKeys = Pick>; + +export type Options< + TData extends TDataShape = TDataShape, + ThrowOnError extends boolean = boolean, + TResponse = unknown, + TResponseStyle extends ResponseStyle = 'fields', +> = OmitKeys< + RequestOptions, + 'body' | 'path' | 'query' | 'url' +> & + ([TData] extends [never] ? unknown : Omit); diff --git a/packages/openapi-ts-tests/sdks/__snapshots__/opencode/export-all/client/utils.gen.ts b/packages/openapi-ts-tests/sdks/__snapshots__/opencode/export-all/client/utils.gen.ts new file mode 100644 index 000000000..4c48a9ee1 --- /dev/null +++ b/packages/openapi-ts-tests/sdks/__snapshots__/opencode/export-all/client/utils.gen.ts @@ -0,0 +1,332 @@ +// This file is auto-generated by @hey-api/openapi-ts + +import { getAuthToken } from '../core/auth.gen'; +import type { QuerySerializerOptions } from '../core/bodySerializer.gen'; +import { jsonBodySerializer } from '../core/bodySerializer.gen'; +import { + serializeArrayParam, + serializeObjectParam, + serializePrimitiveParam, +} from '../core/pathSerializer.gen'; +import { getUrl } from '../core/utils.gen'; +import type { Client, ClientOptions, Config, RequestOptions } from './types.gen'; + +export const createQuerySerializer = ({ + parameters = {}, + ...args +}: QuerySerializerOptions = {}) => { + const querySerializer = (queryParams: T) => { + const search: string[] = []; + if (queryParams && typeof queryParams === 'object') { + for (const name in queryParams) { + const value = queryParams[name]; + + if (value === undefined || value === null) { + continue; + } + + const options = parameters[name] || args; + + if (Array.isArray(value)) { + const serializedArray = serializeArrayParam({ + allowReserved: options.allowReserved, + explode: true, + name, + style: 'form', + value, + ...options.array, + }); + if (serializedArray) search.push(serializedArray); + } else if (typeof value === 'object') { + const serializedObject = serializeObjectParam({ + allowReserved: options.allowReserved, + explode: true, + name, + style: 'deepObject', + value: value as Record, + ...options.object, + }); + if (serializedObject) search.push(serializedObject); + } else { + const serializedPrimitive = serializePrimitiveParam({ + allowReserved: options.allowReserved, + name, + value: value as string, + }); + if (serializedPrimitive) search.push(serializedPrimitive); + } + } + } + return search.join('&'); + }; + return querySerializer; +}; + +/** + * Infers parseAs value from provided Content-Type header. + */ +export const getParseAs = ( + contentType: string | null, +): Exclude => { + if (!contentType) { + // If no Content-Type header is provided, the best we can do is return the raw response body, + // which is effectively the same as the 'stream' option. + return 'stream'; + } + + const cleanContent = contentType.split(';')[0]?.trim(); + + if (!cleanContent) { + return; + } + + if ( + cleanContent.startsWith('application/json') || + cleanContent.endsWith('+json') + ) { + return 'json'; + } + + if (cleanContent === 'multipart/form-data') { + return 'formData'; + } + + if ( + ['application/', 'audio/', 'image/', 'video/'].some((type) => + cleanContent.startsWith(type), + ) + ) { + return 'blob'; + } + + if (cleanContent.startsWith('text/')) { + return 'text'; + } + + return; +}; + +const checkForExistence = ( + options: Pick & { + headers: Headers; + }, + name?: string, +): boolean => { + if (!name) { + return false; + } + if ( + options.headers.has(name) || + options.query?.[name] || + options.headers.get('Cookie')?.includes(`${name}=`) + ) { + return true; + } + return false; +}; + +export const setAuthParams = async ({ + security, + ...options +}: Pick, 'security'> & + Pick & { + headers: Headers; + }) => { + for (const auth of security) { + if (checkForExistence(options, auth.name)) { + continue; + } + + const token = await getAuthToken(auth, options.auth); + + if (!token) { + continue; + } + + const name = auth.name ?? 'Authorization'; + + switch (auth.in) { + case 'query': + if (!options.query) { + options.query = {}; + } + options.query[name] = token; + break; + case 'cookie': + options.headers.append('Cookie', `${name}=${token}`); + break; + case 'header': + default: + options.headers.set(name, token); + break; + } + } +}; + +export const buildUrl: Client['buildUrl'] = (options) => + getUrl({ + baseUrl: options.baseUrl as string, + path: options.path, + query: options.query, + querySerializer: + typeof options.querySerializer === 'function' + ? options.querySerializer + : createQuerySerializer(options.querySerializer), + url: options.url, + }); + +export const mergeConfigs = (a: Config, b: Config): Config => { + const config = { ...a, ...b }; + if (config.baseUrl?.endsWith('/')) { + config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1); + } + config.headers = mergeHeaders(a.headers, b.headers); + return config; +}; + +const headersEntries = (headers: Headers): Array<[string, string]> => { + const entries: Array<[string, string]> = []; + headers.forEach((value, key) => { + entries.push([key, value]); + }); + return entries; +}; + +export const mergeHeaders = ( + ...headers: Array['headers'] | undefined> +): Headers => { + const mergedHeaders = new Headers(); + for (const header of headers) { + if (!header) { + continue; + } + + const iterator = + header instanceof Headers + ? headersEntries(header) + : Object.entries(header); + + for (const [key, value] of iterator) { + if (value === null) { + mergedHeaders.delete(key); + } else if (Array.isArray(value)) { + for (const v of value) { + mergedHeaders.append(key, v as string); + } + } else if (value !== undefined) { + // assume object headers are meant to be JSON stringified, i.e. their + // content value in OpenAPI specification is 'application/json' + mergedHeaders.set( + key, + typeof value === 'object' ? JSON.stringify(value) : (value as string), + ); + } + } + } + return mergedHeaders; +}; + +type ErrInterceptor = ( + error: Err, + response: Res, + request: Req, + options: Options, +) => Err | Promise; + +type ReqInterceptor = ( + request: Req, + options: Options, +) => Req | Promise; + +type ResInterceptor = ( + response: Res, + request: Req, + options: Options, +) => Res | Promise; + +class Interceptors { + fns: Array = []; + + clear(): void { + this.fns = []; + } + + eject(id: number | Interceptor): void { + const index = this.getInterceptorIndex(id); + if (this.fns[index]) { + this.fns[index] = null; + } + } + + exists(id: number | Interceptor): boolean { + const index = this.getInterceptorIndex(id); + return Boolean(this.fns[index]); + } + + getInterceptorIndex(id: number | Interceptor): number { + if (typeof id === 'number') { + return this.fns[id] ? id : -1; + } + return this.fns.indexOf(id); + } + + update( + id: number | Interceptor, + fn: Interceptor, + ): number | Interceptor | false { + const index = this.getInterceptorIndex(id); + if (this.fns[index]) { + this.fns[index] = fn; + return id; + } + return false; + } + + use(fn: Interceptor): number { + this.fns.push(fn); + return this.fns.length - 1; + } +} + +export interface Middleware { + error: Interceptors>; + request: Interceptors>; + response: Interceptors>; +} + +export const createInterceptors = (): Middleware< + Req, + Res, + Err, + Options +> => ({ + error: new Interceptors>(), + request: new Interceptors>(), + response: new Interceptors>(), +}); + +const defaultQuerySerializer = createQuerySerializer({ + allowReserved: false, + array: { + explode: true, + style: 'form', + }, + object: { + explode: true, + style: 'deepObject', + }, +}); + +const defaultHeaders = { + 'Content-Type': 'application/json', +}; + +export const createConfig = ( + override: Config & T> = {}, +): Config & T> => ({ + ...jsonBodySerializer, + headers: defaultHeaders, + parseAs: 'auto', + querySerializer: defaultQuerySerializer, + ...override, +}); diff --git a/packages/openapi-ts-tests/sdks/__snapshots__/opencode/export-all/core/auth.gen.ts b/packages/openapi-ts-tests/sdks/__snapshots__/opencode/export-all/core/auth.gen.ts new file mode 100644 index 000000000..f8a73266f --- /dev/null +++ b/packages/openapi-ts-tests/sdks/__snapshots__/opencode/export-all/core/auth.gen.ts @@ -0,0 +1,42 @@ +// This file is auto-generated by @hey-api/openapi-ts + +export type AuthToken = string | undefined; + +export interface Auth { + /** + * Which part of the request do we use to send the auth? + * + * @default 'header' + */ + in?: 'header' | 'query' | 'cookie'; + /** + * Header or query parameter name. + * + * @default 'Authorization' + */ + name?: string; + scheme?: 'basic' | 'bearer'; + type: 'apiKey' | 'http'; +} + +export const getAuthToken = async ( + auth: Auth, + callback: ((auth: Auth) => Promise | AuthToken) | AuthToken, +): Promise => { + const token = + typeof callback === 'function' ? await callback(auth) : callback; + + if (!token) { + return; + } + + if (auth.scheme === 'bearer') { + return `Bearer ${token}`; + } + + if (auth.scheme === 'basic') { + return `Basic ${btoa(token)}`; + } + + return token; +}; diff --git a/packages/openapi-ts-tests/sdks/__snapshots__/opencode/export-all/core/bodySerializer.gen.ts b/packages/openapi-ts-tests/sdks/__snapshots__/opencode/export-all/core/bodySerializer.gen.ts new file mode 100644 index 000000000..552b50f7c --- /dev/null +++ b/packages/openapi-ts-tests/sdks/__snapshots__/opencode/export-all/core/bodySerializer.gen.ts @@ -0,0 +1,100 @@ +// This file is auto-generated by @hey-api/openapi-ts + +import type { + ArrayStyle, + ObjectStyle, + SerializerOptions, +} from './pathSerializer.gen'; + +export type QuerySerializer = (query: Record) => string; + +export type BodySerializer = (body: any) => any; + +type QuerySerializerOptionsObject = { + allowReserved?: boolean; + array?: Partial>; + object?: Partial>; +}; + +export type QuerySerializerOptions = QuerySerializerOptionsObject & { + /** + * Per-parameter serialization overrides. When provided, these settings + * override the global array/object settings for specific parameter names. + */ + parameters?: Record; +}; + +const serializeFormDataPair = ( + data: FormData, + key: string, + value: unknown, +): void => { + if (typeof value === 'string' || value instanceof Blob) { + data.append(key, value); + } else if (value instanceof Date) { + data.append(key, value.toISOString()); + } else { + data.append(key, JSON.stringify(value)); + } +}; + +const serializeUrlSearchParamsPair = ( + data: URLSearchParams, + key: string, + value: unknown, +): void => { + if (typeof value === 'string') { + data.append(key, value); + } else { + data.append(key, JSON.stringify(value)); + } +}; + +export const formDataBodySerializer = { + bodySerializer: | Array>>( + body: T, + ): FormData => { + const data = new FormData(); + + Object.entries(body).forEach(([key, value]) => { + if (value === undefined || value === null) { + return; + } + if (Array.isArray(value)) { + value.forEach((v) => serializeFormDataPair(data, key, v)); + } else { + serializeFormDataPair(data, key, value); + } + }); + + return data; + }, +}; + +export const jsonBodySerializer = { + bodySerializer: (body: T): string => + JSON.stringify(body, (_key, value) => + typeof value === 'bigint' ? value.toString() : value, + ), +}; + +export const urlSearchParamsBodySerializer = { + bodySerializer: | Array>>( + body: T, + ): string => { + const data = new URLSearchParams(); + + Object.entries(body).forEach(([key, value]) => { + if (value === undefined || value === null) { + return; + } + if (Array.isArray(value)) { + value.forEach((v) => serializeUrlSearchParamsPair(data, key, v)); + } else { + serializeUrlSearchParamsPair(data, key, value); + } + }); + + return data.toString(); + }, +}; diff --git a/packages/openapi-ts-tests/sdks/__snapshots__/opencode/export-all/core/params.gen.ts b/packages/openapi-ts-tests/sdks/__snapshots__/opencode/export-all/core/params.gen.ts new file mode 100644 index 000000000..602715c46 --- /dev/null +++ b/packages/openapi-ts-tests/sdks/__snapshots__/opencode/export-all/core/params.gen.ts @@ -0,0 +1,176 @@ +// This file is auto-generated by @hey-api/openapi-ts + +type Slot = 'body' | 'headers' | 'path' | 'query'; + +export type Field = + | { + in: Exclude; + /** + * Field name. This is the name we want the user to see and use. + */ + key: string; + /** + * Field mapped name. This is the name we want to use in the request. + * If omitted, we use the same value as `key`. + */ + map?: string; + } + | { + in: Extract; + /** + * Key isn't required for bodies. + */ + key?: string; + map?: string; + } + | { + /** + * Field name. This is the name we want the user to see and use. + */ + key: string; + /** + * Field mapped name. This is the name we want to use in the request. + * If `in` is omitted, `map` aliases `key` to the transport layer. + */ + map: Slot; + }; + +export interface Fields { + allowExtra?: Partial>; + args?: ReadonlyArray; +} + +export type FieldsConfig = ReadonlyArray; + +const extraPrefixesMap: Record = { + $body_: 'body', + $headers_: 'headers', + $path_: 'path', + $query_: 'query', +}; +const extraPrefixes = Object.entries(extraPrefixesMap); + +type KeyMap = Map< + string, + | { + in: Slot; + map?: string; + } + | { + in?: never; + map: Slot; + } +>; + +const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => { + if (!map) { + map = new Map(); + } + + for (const config of fields) { + if ('in' in config) { + if (config.key) { + map.set(config.key, { + in: config.in, + map: config.map, + }); + } + } else if ('key' in config) { + map.set(config.key, { + map: config.map, + }); + } else if (config.args) { + buildKeyMap(config.args, map); + } + } + + return map; +}; + +interface Params { + body: unknown; + headers: Record; + path: Record; + query: Record; +} + +const stripEmptySlots = (params: Params) => { + for (const [slot, value] of Object.entries(params)) { + if (value && typeof value === 'object' && !Object.keys(value).length) { + delete params[slot as Slot]; + } + } +}; + +export const buildClientParams = ( + args: ReadonlyArray, + fields: FieldsConfig, +) => { + const params: Params = { + body: {}, + headers: {}, + path: {}, + query: {}, + }; + + const map = buildKeyMap(fields); + + let config: FieldsConfig[number] | undefined; + + for (const [index, arg] of args.entries()) { + if (fields[index]) { + config = fields[index]; + } + + if (!config) { + continue; + } + + if ('in' in config) { + if (config.key) { + const field = map.get(config.key)!; + const name = field.map || config.key; + if (field.in) { + (params[field.in] as Record)[name] = arg; + } + } else { + params.body = arg; + } + } else { + for (const [key, value] of Object.entries(arg ?? {})) { + const field = map.get(key); + + if (field) { + if (field.in) { + const name = field.map || key; + (params[field.in] as Record)[name] = value; + } else { + params[field.map] = value; + } + } else { + const extra = extraPrefixes.find(([prefix]) => + key.startsWith(prefix), + ); + + if (extra) { + const [prefix, slot] = extra; + (params[slot] as Record)[ + key.slice(prefix.length) + ] = value; + } else if ('allowExtra' in config && config.allowExtra) { + for (const [slot, allowed] of Object.entries(config.allowExtra)) { + if (allowed) { + (params[slot as Slot] as Record)[key] = value; + break; + } + } + } + } + } + } + } + + stripEmptySlots(params); + + return params; +}; diff --git a/packages/openapi-ts-tests/sdks/__snapshots__/opencode/export-all/core/pathSerializer.gen.ts b/packages/openapi-ts-tests/sdks/__snapshots__/opencode/export-all/core/pathSerializer.gen.ts new file mode 100644 index 000000000..8d9993104 --- /dev/null +++ b/packages/openapi-ts-tests/sdks/__snapshots__/opencode/export-all/core/pathSerializer.gen.ts @@ -0,0 +1,181 @@ +// This file is auto-generated by @hey-api/openapi-ts + +interface SerializeOptions + extends SerializePrimitiveOptions, + SerializerOptions {} + +interface SerializePrimitiveOptions { + allowReserved?: boolean; + name: string; +} + +export interface SerializerOptions { + /** + * @default true + */ + explode: boolean; + style: T; +} + +export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited'; +export type ArraySeparatorStyle = ArrayStyle | MatrixStyle; +type MatrixStyle = 'label' | 'matrix' | 'simple'; +export type ObjectStyle = 'form' | 'deepObject'; +type ObjectSeparatorStyle = ObjectStyle | MatrixStyle; + +interface SerializePrimitiveParam extends SerializePrimitiveOptions { + value: string; +} + +export const separatorArrayExplode = (style: ArraySeparatorStyle) => { + switch (style) { + case 'label': + return '.'; + case 'matrix': + return ';'; + case 'simple': + return ','; + default: + return '&'; + } +}; + +export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => { + switch (style) { + case 'form': + return ','; + case 'pipeDelimited': + return '|'; + case 'spaceDelimited': + return '%20'; + default: + return ','; + } +}; + +export const separatorObjectExplode = (style: ObjectSeparatorStyle) => { + switch (style) { + case 'label': + return '.'; + case 'matrix': + return ';'; + case 'simple': + return ','; + default: + return '&'; + } +}; + +export const serializeArrayParam = ({ + allowReserved, + explode, + name, + style, + value, +}: SerializeOptions & { + value: unknown[]; +}) => { + if (!explode) { + const joinedValues = ( + allowReserved ? value : value.map((v) => encodeURIComponent(v as string)) + ).join(separatorArrayNoExplode(style)); + switch (style) { + case 'label': + return `.${joinedValues}`; + case 'matrix': + return `;${name}=${joinedValues}`; + case 'simple': + return joinedValues; + default: + return `${name}=${joinedValues}`; + } + } + + const separator = separatorArrayExplode(style); + const joinedValues = value + .map((v) => { + if (style === 'label' || style === 'simple') { + return allowReserved ? v : encodeURIComponent(v as string); + } + + return serializePrimitiveParam({ + allowReserved, + name, + value: v as string, + }); + }) + .join(separator); + return style === 'label' || style === 'matrix' + ? separator + joinedValues + : joinedValues; +}; + +export const serializePrimitiveParam = ({ + allowReserved, + name, + value, +}: SerializePrimitiveParam) => { + if (value === undefined || value === null) { + return ''; + } + + if (typeof value === 'object') { + throw new Error( + 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.', + ); + } + + return `${name}=${allowReserved ? value : encodeURIComponent(value)}`; +}; + +export const serializeObjectParam = ({ + allowReserved, + explode, + name, + style, + value, + valueOnly, +}: SerializeOptions & { + value: Record | Date; + valueOnly?: boolean; +}) => { + if (value instanceof Date) { + return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`; + } + + if (style !== 'deepObject' && !explode) { + let values: string[] = []; + Object.entries(value).forEach(([key, v]) => { + values = [ + ...values, + key, + allowReserved ? (v as string) : encodeURIComponent(v as string), + ]; + }); + const joinedValues = values.join(','); + switch (style) { + case 'form': + return `${name}=${joinedValues}`; + case 'label': + return `.${joinedValues}`; + case 'matrix': + return `;${name}=${joinedValues}`; + default: + return joinedValues; + } + } + + const separator = separatorObjectExplode(style); + const joinedValues = Object.entries(value) + .map(([key, v]) => + serializePrimitiveParam({ + allowReserved, + name: style === 'deepObject' ? `${name}[${key}]` : key, + value: v as string, + }), + ) + .join(separator); + return style === 'label' || style === 'matrix' + ? separator + joinedValues + : joinedValues; +}; diff --git a/packages/openapi-ts-tests/sdks/__snapshots__/opencode/export-all/core/queryKeySerializer.gen.ts b/packages/openapi-ts-tests/sdks/__snapshots__/opencode/export-all/core/queryKeySerializer.gen.ts new file mode 100644 index 000000000..d3bb68396 --- /dev/null +++ b/packages/openapi-ts-tests/sdks/__snapshots__/opencode/export-all/core/queryKeySerializer.gen.ts @@ -0,0 +1,136 @@ +// This file is auto-generated by @hey-api/openapi-ts + +/** + * JSON-friendly union that mirrors what Pinia Colada can hash. + */ +export type JsonValue = + | null + | string + | number + | boolean + | JsonValue[] + | { [key: string]: JsonValue }; + +/** + * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes. + */ +export const queryKeyJsonReplacer = (_key: string, value: unknown) => { + if ( + value === undefined || + typeof value === 'function' || + typeof value === 'symbol' + ) { + return undefined; + } + if (typeof value === 'bigint') { + return value.toString(); + } + if (value instanceof Date) { + return value.toISOString(); + } + return value; +}; + +/** + * Safely stringifies a value and parses it back into a JsonValue. + */ +export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => { + try { + const json = JSON.stringify(input, queryKeyJsonReplacer); + if (json === undefined) { + return undefined; + } + return JSON.parse(json) as JsonValue; + } catch { + return undefined; + } +}; + +/** + * Detects plain objects (including objects with a null prototype). + */ +const isPlainObject = (value: unknown): value is Record => { + if (value === null || typeof value !== 'object') { + return false; + } + const prototype = Object.getPrototypeOf(value as object); + return prototype === Object.prototype || prototype === null; +}; + +/** + * Turns URLSearchParams into a sorted JSON object for deterministic keys. + */ +const serializeSearchParams = (params: URLSearchParams): JsonValue => { + const entries = Array.from(params.entries()).sort(([a], [b]) => + a.localeCompare(b), + ); + const result: Record = {}; + + for (const [key, value] of entries) { + const existing = result[key]; + if (existing === undefined) { + result[key] = value; + continue; + } + + if (Array.isArray(existing)) { + (existing as string[]).push(value); + } else { + result[key] = [existing, value]; + } + } + + return result; +}; + +/** + * Normalizes any accepted value into a JSON-friendly shape for query keys. + */ +export const serializeQueryKeyValue = ( + value: unknown, +): JsonValue | undefined => { + if (value === null) { + return null; + } + + if ( + typeof value === 'string' || + typeof value === 'number' || + typeof value === 'boolean' + ) { + return value; + } + + if ( + value === undefined || + typeof value === 'function' || + typeof value === 'symbol' + ) { + return undefined; + } + + if (typeof value === 'bigint') { + return value.toString(); + } + + if (value instanceof Date) { + return value.toISOString(); + } + + if (Array.isArray(value)) { + return stringifyToJsonValue(value); + } + + if ( + typeof URLSearchParams !== 'undefined' && + value instanceof URLSearchParams + ) { + return serializeSearchParams(value); + } + + if (isPlainObject(value)) { + return stringifyToJsonValue(value); + } + + return undefined; +}; diff --git a/packages/openapi-ts-tests/sdks/__snapshots__/opencode/export-all/core/serverSentEvents.gen.ts b/packages/openapi-ts-tests/sdks/__snapshots__/opencode/export-all/core/serverSentEvents.gen.ts new file mode 100644 index 000000000..343d25af8 --- /dev/null +++ b/packages/openapi-ts-tests/sdks/__snapshots__/opencode/export-all/core/serverSentEvents.gen.ts @@ -0,0 +1,266 @@ +// This file is auto-generated by @hey-api/openapi-ts + +import type { Config } from './types.gen'; + +export type ServerSentEventsOptions = Omit< + RequestInit, + 'method' +> & + Pick & { + /** + * Fetch API implementation. You can use this option to provide a custom + * fetch instance. + * + * @default globalThis.fetch + */ + fetch?: typeof fetch; + /** + * Implementing clients can call request interceptors inside this hook. + */ + onRequest?: (url: string, init: RequestInit) => Promise; + /** + * 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) => void; + serializedBody?: RequestInit['body']; + /** + * Default retry delay in milliseconds. + * + * This option applies only if the endpoint returns a stream of events. + * + * @default 3000 + */ + sseDefaultRetryDelay?: number; + /** + * Maximum number of retry attempts before giving up. + */ + sseMaxRetryAttempts?: number; + /** + * Maximum retry delay in milliseconds. + * + * Applies only when exponential backoff is used. + * + * This option applies only if the endpoint returns a stream of events. + * + * @default 30000 + */ + sseMaxRetryDelay?: number; + /** + * Optional sleep function for retry backoff. + * + * Defaults to using `setTimeout`. + */ + sseSleepFn?: (ms: number) => Promise; + url: string; + }; + +export interface StreamEvent { + data: TData; + event?: string; + id?: string; + retry?: number; +} + +export type ServerSentEventsResult< + TData = unknown, + TReturn = void, + TNext = unknown, +> = { + stream: AsyncGenerator< + TData extends Record ? TData[keyof TData] : TData, + TReturn, + TNext + >; +}; + +export const createSseClient = ({ + onRequest, + onSseError, + onSseEvent, + responseTransformer, + responseValidator, + sseDefaultRetryDelay, + sseMaxRetryAttempts, + sseMaxRetryDelay, + sseSleepFn, + url, + ...options +}: ServerSentEventsOptions): ServerSentEventsResult => { + 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 | undefined); + + if (lastEventId !== undefined) { + headers.set('Last-Event-ID', lastEventId); + } + + try { + const requestInit: RequestInit = { + redirect: 'follow', + ...options, + body: options.serializedBody, + headers, + signal, + }; + let request = new Request(url, requestInit); + if (onRequest) { + request = await onRequest(url, requestInit); + } + // fetch must be assigned here, otherwise it would throw the error: + // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation + const _fetch = options.fetch ?? globalThis.fetch; + const response = await _fetch(request); + + if (!response.ok) + throw new Error( + `SSE failed: ${response.status} ${response.statusText}`, + ); + + if (!response.body) throw new Error('No body in SSE response'); + + const reader = response.body + .pipeThrough(new TextDecoderStream()) + .getReader(); + + let buffer = ''; + + const abortHandler = () => { + try { + reader.cancel(); + } catch { + // noop + } + }; + + signal.addEventListener('abort', abortHandler); + + try { + while (true) { + const { done, value } = await reader.read(); + if (done) break; + buffer += value; + // Normalize line endings: CRLF -> LF, then CR -> LF + buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); + + const chunks = buffer.split('\n\n'); + buffer = chunks.pop() ?? ''; + + for (const chunk of chunks) { + const lines = chunk.split('\n'); + const dataLines: Array = []; + 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 }; +}; diff --git a/packages/openapi-ts-tests/sdks/__snapshots__/opencode/export-all/core/types.gen.ts b/packages/openapi-ts-tests/sdks/__snapshots__/opencode/export-all/core/types.gen.ts new file mode 100644 index 000000000..643c070c9 --- /dev/null +++ b/packages/openapi-ts-tests/sdks/__snapshots__/opencode/export-all/core/types.gen.ts @@ -0,0 +1,118 @@ +// This file is auto-generated by @hey-api/openapi-ts + +import type { Auth, AuthToken } from './auth.gen'; +import type { + BodySerializer, + QuerySerializer, + QuerySerializerOptions, +} from './bodySerializer.gen'; + +export type HttpMethod = + | 'connect' + | 'delete' + | 'get' + | 'head' + | 'options' + | 'patch' + | 'post' + | 'put' + | 'trace'; + +export type Client< + RequestFn = never, + Config = unknown, + MethodFn = never, + BuildUrlFn = never, + SseFn = never, +> = { + /** + * Returns the final request URL. + */ + buildUrl: BuildUrlFn; + getConfig: () => Config; + request: RequestFn; + setConfig: (config: Config) => Config; +} & { + [K in HttpMethod]: MethodFn; +} & ([SseFn] extends [never] + ? { sse?: never } + : { sse: { [K in HttpMethod]: SseFn } }); + +export interface Config { + /** + * Auth token or a function returning auth token. The resolved value will be + * added to the request payload as defined by its `security` array. + */ + auth?: ((auth: Auth) => Promise | AuthToken) | AuthToken; + /** + * A function for serializing request body parameter. By default, + * {@link JSON.stringify()} will be used. + */ + bodySerializer?: BodySerializer | null; + /** + * An object containing any HTTP headers that you want to pre-populate your + * `Headers` object with. + * + * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more} + */ + headers?: + | RequestInit['headers'] + | Record< + string, + | string + | number + | boolean + | (string | number | boolean)[] + | null + | undefined + | unknown + >; + /** + * The request method. + * + * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more} + */ + method?: Uppercase; + /** + * A function for serializing request query parameters. By default, arrays + * will be exploded in form style, objects will be exploded in deepObject + * style, and reserved characters are percent-encoded. + * + * This method will have no effect if the native `paramsSerializer()` Axios + * API function is used. + * + * {@link https://swagger.io/docs/specification/serialization/#query View examples} + */ + querySerializer?: QuerySerializer | QuerySerializerOptions; + /** + * A function validating request data. This is useful if you want to ensure + * the request conforms to the desired shape, so it can be safely sent to + * the server. + */ + requestValidator?: (data: unknown) => Promise; + /** + * A function transforming response data before it's returned. This is useful + * for post-processing data, e.g. converting ISO strings into Date objects. + */ + responseTransformer?: (data: unknown) => Promise; + /** + * A function validating response data. This is useful if you want to ensure + * the response conforms to the desired shape, so it can be safely passed to + * the transformers and returned to the user. + */ + responseValidator?: (data: unknown) => Promise; +} + +type IsExactlyNeverOrNeverUndefined = [T] extends [never] + ? true + : [T] extends [never | undefined] + ? [undefined] extends [T] + ? false + : true + : false; + +export type OmitNever> = { + [K in keyof T as IsExactlyNeverOrNeverUndefined extends true + ? never + : K]: T[K]; +}; diff --git a/packages/openapi-ts-tests/sdks/__snapshots__/opencode/export-all/core/utils.gen.ts b/packages/openapi-ts-tests/sdks/__snapshots__/opencode/export-all/core/utils.gen.ts new file mode 100644 index 000000000..0b5389d08 --- /dev/null +++ b/packages/openapi-ts-tests/sdks/__snapshots__/opencode/export-all/core/utils.gen.ts @@ -0,0 +1,143 @@ +// This file is auto-generated by @hey-api/openapi-ts + +import type { BodySerializer, QuerySerializer } from './bodySerializer.gen'; +import { + type ArraySeparatorStyle, + serializeArrayParam, + serializeObjectParam, + serializePrimitiveParam, +} from './pathSerializer.gen'; + +export interface PathSerializer { + path: Record; + 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, + 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; + query?: Record; + querySerializer: QuerySerializer; + url: string; +}) => { + const pathUrl = _url.startsWith('/') ? _url : `/${_url}`; + let url = (baseUrl ?? '') + pathUrl; + if (path) { + url = defaultPathSerializer({ path, url }); + } + let search = query ? querySerializer(query) : ''; + if (search.startsWith('?')) { + search = search.substring(1); + } + if (search) { + url += `?${search}`; + } + return url; +}; + +export function getValidRequestBody(options: { + body?: unknown; + bodySerializer?: BodySerializer | null; + serializedBody?: unknown; +}) { + const hasBody = options.body !== undefined; + const isSerializedBody = hasBody && options.bodySerializer; + + if (isSerializedBody) { + if ('serializedBody' in options) { + const hasSerializedBody = + options.serializedBody !== undefined && options.serializedBody !== ''; + + return hasSerializedBody ? options.serializedBody : null; + } + + // not all clients implement a serializedBody property (i.e. client-axios) + return options.body !== '' ? options.body : null; + } + + // plain/text body + if (hasBody) { + return options.body; + } + + // no body was provided + return undefined; +} diff --git a/packages/openapi-ts-tests/sdks/__snapshots__/opencode/export-all/index.ts b/packages/openapi-ts-tests/sdks/__snapshots__/opencode/export-all/index.ts new file mode 100644 index 000000000..57ed02bf5 --- /dev/null +++ b/packages/openapi-ts-tests/sdks/__snapshots__/opencode/export-all/index.ts @@ -0,0 +1,4 @@ +// This file is auto-generated by @hey-api/openapi-ts + +export * from './sdk.gen'; +export type * from './types.gen'; diff --git a/packages/openapi-ts-tests/sdks/__snapshots__/opencode/export-all/sdk.gen.ts b/packages/openapi-ts-tests/sdks/__snapshots__/opencode/export-all/sdk.gen.ts new file mode 100644 index 000000000..56ce2c581 --- /dev/null +++ b/packages/openapi-ts-tests/sdks/__snapshots__/opencode/export-all/sdk.gen.ts @@ -0,0 +1,594 @@ +// This file is auto-generated by @hey-api/openapi-ts + +import { buildClientParams, type Client, type Options as Options2, type TDataShape } from './client'; +import { client } from './client.gen'; +import type { AgentPartInput, AppAgentsResponses, AppGetResponses, AppInitResponses, AppLogResponses, Auth, AuthSetErrors, AuthSetResponses, ConfigGetResponses, ConfigProvidersResponses, EventSubscribeResponses, FilePartInput, FileReadResponses, FileStatusResponses, FindFilesResponses, FindSymbolsResponses, FindTextResponses, PostSessionByIdPermissionsByPermissionIdResponses, SessionAbortResponses, SessionChatResponses, SessionChildrenResponses, SessionCreateErrors, SessionCreateResponses, SessionDeleteResponses, SessionGetResponses, SessionInitResponses, SessionListResponses, SessionMessageResponses, SessionMessagesResponses, SessionRevertResponses, SessionShareResponses, SessionShellResponses, SessionSummarizeResponses, SessionUnrevertResponses, SessionUnshareResponses, SessionUpdateResponses, TextPartInput, TuiAppendPromptResponses, TuiClearPromptResponses, TuiExecuteCommandResponses, TuiOpenHelpResponses, TuiOpenModelsResponses, TuiOpenSessionsResponses, TuiOpenThemesResponses, TuiShowToastResponses, TuiSubmitPromptResponses } from './types.gen'; + +export type Options = Options2 & { + /** + * You can provide a client instance returned by `createClient()` instead of + * individual options. This might be also useful if you want to implement a + * custom client. + */ + client?: Client; + /** + * 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. + */ + meta?: Record; +}; + +/** + * Get events + */ +export const eventSubscribe = (options?: Options) => (options?.client ?? client).sse.get({ url: '/event', ...options }); + +/** + * Get app info + */ +export const appGet = (options?: Options) => (options?.client ?? client).get({ url: '/app', ...options }); + +/** + * Initialize the app + */ +export const appInit = (options?: Options) => (options?.client ?? client).post({ url: '/app/init', ...options }); + +/** + * Get config info + */ +export const configGet = (options?: Options) => (options?.client ?? client).get({ url: '/config', ...options }); + +/** + * List all sessions + */ +export const sessionList = (options?: Options) => (options?.client ?? client).get({ url: '/session', ...options }); + +/** + * Create a new session + */ +export const sessionCreate = (parameters?: { + parentID?: string; + title?: string; +}, options?: Options) => { + const params = buildClientParams([parameters], [{ args: [{ in: 'body', key: 'parentID' }, { in: 'body', key: 'title' }] }]); + return (options?.client ?? client).post({ + url: '/session', + ...options, + ...params, + headers: { + 'Content-Type': 'application/json', + ...options?.headers, + ...params.headers + } + }); +}; + +/** + * Delete a session and all its data + */ +export const sessionDelete = (parameters: { + id: string; +}, options?: Options) => { + const params = buildClientParams([parameters], [{ args: [{ in: 'path', key: 'id' }] }]); + return (options?.client ?? client).delete({ + url: '/session/{id}', + ...options, + ...params + }); +}; + +/** + * Get session + */ +export const sessionGet = (parameters: { + id: string; +}, options?: Options) => { + const params = buildClientParams([parameters], [{ args: [{ in: 'path', key: 'id' }] }]); + return (options?.client ?? client).get({ + url: '/session/{id}', + ...options, + ...params + }); +}; + +/** + * Update session properties + */ +export const sessionUpdate = (parameters: { + id: string; + title?: string; +}, options?: Options) => { + const params = buildClientParams([parameters], [{ args: [{ in: 'path', key: 'id' }, { in: 'body', key: 'title' }] }]); + return (options?.client ?? client).patch({ + url: '/session/{id}', + ...options, + ...params, + headers: { + 'Content-Type': 'application/json', + ...options?.headers, + ...params.headers + } + }); +}; + +/** + * Get a session's children + */ +export const sessionChildren = (parameters: { + id: string; +}, options?: Options) => { + const params = buildClientParams([parameters], [{ args: [{ in: 'path', key: 'id' }] }]); + return (options?.client ?? client).get({ + url: '/session/{id}/children', + ...options, + ...params + }); +}; + +/** + * Analyze the app and create an AGENTS.md file + */ +export const sessionInit = (parameters: { + id: string; + messageID?: string; + providerID?: string; + modelID?: string; +}, options?: Options) => { + const params = buildClientParams([parameters], [{ args: [ + { in: 'path', key: 'id' }, + { in: 'body', key: 'messageID' }, + { in: 'body', key: 'providerID' }, + { in: 'body', key: 'modelID' } + ] }]); + return (options?.client ?? client).post({ + url: '/session/{id}/init', + ...options, + ...params, + headers: { + 'Content-Type': 'application/json', + ...options?.headers, + ...params.headers + } + }); +}; + +/** + * Abort a session + */ +export const sessionAbort = (parameters: { + id: string; +}, options?: Options) => { + const params = buildClientParams([parameters], [{ args: [{ in: 'path', key: 'id' }] }]); + return (options?.client ?? client).post({ + url: '/session/{id}/abort', + ...options, + ...params + }); +}; + +/** + * Unshare the session + */ +export const sessionUnshare = (parameters: { + id: string; +}, options?: Options) => { + const params = buildClientParams([parameters], [{ args: [{ in: 'path', key: 'id' }] }]); + return (options?.client ?? client).delete({ + url: '/session/{id}/share', + ...options, + ...params + }); +}; + +/** + * Share a session + */ +export const sessionShare = (parameters: { + id: string; +}, options?: Options) => { + const params = buildClientParams([parameters], [{ args: [{ in: 'path', key: 'id' }] }]); + return (options?.client ?? client).post({ + url: '/session/{id}/share', + ...options, + ...params + }); +}; + +/** + * Summarize the session + */ +export const sessionSummarize = (parameters: { + id: string; + providerID?: string; + modelID?: string; +}, options?: Options) => { + const params = buildClientParams([parameters], [{ args: [ + { in: 'path', key: 'id' }, + { in: 'body', key: 'providerID' }, + { in: 'body', key: 'modelID' } + ] }]); + return (options?.client ?? client).post({ + url: '/session/{id}/summarize', + ...options, + ...params, + headers: { + 'Content-Type': 'application/json', + ...options?.headers, + ...params.headers + } + }); +}; + +/** + * List messages for a session + */ +export const sessionMessages = (parameters: { + id: string; +}, options?: Options) => { + const params = buildClientParams([parameters], [{ args: [{ in: 'path', key: 'id' }] }]); + return (options?.client ?? client).get({ + url: '/session/{id}/message', + ...options, + ...params + }); +}; + +/** + * Create and send a new message to a session + */ +export const sessionChat = (parameters: { + id: string; + messageID?: string; + providerID?: string; + modelID?: string; + agent?: string; + system?: string; + tools?: { + [key: string]: boolean; + }; + parts?: Array<({ + type: 'text'; + } & TextPartInput) | ({ + type: 'file'; + } & FilePartInput) | ({ + type: 'agent'; + } & AgentPartInput)>; +}, options?: Options) => { + const params = buildClientParams([parameters], [{ args: [ + { in: 'path', key: 'id' }, + { in: 'body', key: 'messageID' }, + { in: 'body', key: 'providerID' }, + { in: 'body', key: 'modelID' }, + { in: 'body', key: 'agent' }, + { in: 'body', key: 'system' }, + { in: 'body', key: 'tools' }, + { in: 'body', key: 'parts' } + ] }]); + return (options?.client ?? client).post({ + url: '/session/{id}/message', + ...options, + ...params, + headers: { + 'Content-Type': 'application/json', + ...options?.headers, + ...params.headers + } + }); +}; + +/** + * Get a message from a session + */ +export const sessionMessage = (parameters: { + id: string; + messageID: string; +}, options?: Options) => { + const params = buildClientParams([parameters], [{ args: [{ in: 'path', key: 'id' }, { in: 'path', key: 'messageID' }] }]); + return (options?.client ?? client).get({ + url: '/session/{id}/message/{messageID}', + ...options, + ...params + }); +}; + +/** + * Run a shell command + */ +export const sessionShell = (parameters: { + id: string; + agent?: string; + command?: string; +}, options?: Options) => { + const params = buildClientParams([parameters], [{ args: [ + { in: 'path', key: 'id' }, + { in: 'body', key: 'agent' }, + { in: 'body', key: 'command' } + ] }]); + return (options?.client ?? client).post({ + url: '/session/{id}/shell', + ...options, + ...params, + headers: { + 'Content-Type': 'application/json', + ...options?.headers, + ...params.headers + } + }); +}; + +/** + * Revert a message + */ +export const sessionRevert = (parameters: { + id: string; + messageID?: string; + partID?: string; +}, options?: Options) => { + const params = buildClientParams([parameters], [{ args: [ + { in: 'path', key: 'id' }, + { in: 'body', key: 'messageID' }, + { in: 'body', key: 'partID' } + ] }]); + return (options?.client ?? client).post({ + url: '/session/{id}/revert', + ...options, + ...params, + headers: { + 'Content-Type': 'application/json', + ...options?.headers, + ...params.headers + } + }); +}; + +/** + * Restore all reverted messages + */ +export const sessionUnrevert = (parameters: { + id: string; +}, options?: Options) => { + const params = buildClientParams([parameters], [{ args: [{ in: 'path', key: 'id' }] }]); + return (options?.client ?? client).post({ + url: '/session/{id}/unrevert', + ...options, + ...params + }); +}; + +/** + * Respond to a permission request + */ +export const postSessionByIdPermissionsByPermissionId = (parameters: { + id: string; + permissionID: string; + response?: 'once' | 'always' | 'reject'; +}, options?: Options) => { + const params = buildClientParams([parameters], [{ args: [ + { in: 'path', key: 'id' }, + { in: 'path', key: 'permissionID' }, + { in: 'body', key: 'response' } + ] }]); + return (options?.client ?? client).post({ + url: '/session/{id}/permissions/{permissionID}', + ...options, + ...params, + headers: { + 'Content-Type': 'application/json', + ...options?.headers, + ...params.headers + } + }); +}; + +/** + * List all providers + */ +export const configProviders = (options?: Options) => (options?.client ?? client).get({ url: '/config/providers', ...options }); + +/** + * Find text in files + */ +export const findText = (parameters: { + pattern: string; +}, options?: Options) => { + const params = buildClientParams([parameters], [{ args: [{ in: 'query', key: 'pattern' }] }]); + return (options?.client ?? client).get({ + url: '/find', + ...options, + ...params + }); +}; + +/** + * Find files + */ +export const findFiles = (parameters: { + query: string; +}, options?: Options) => { + const params = buildClientParams([parameters], [{ args: [{ in: 'query', key: 'query' }] }]); + return (options?.client ?? client).get({ + url: '/find/file', + ...options, + ...params + }); +}; + +/** + * Find workspace symbols + */ +export const findSymbols = (parameters: { + query: string; +}, options?: Options) => { + const params = buildClientParams([parameters], [{ args: [{ in: 'query', key: 'query' }] }]); + return (options?.client ?? client).get({ + url: '/find/symbol', + ...options, + ...params + }); +}; + +/** + * Read a file + */ +export const fileRead = (parameters: { + path: string; +}, options?: Options) => { + const params = buildClientParams([parameters], [{ args: [{ in: 'query', key: 'path' }] }]); + return (options?.client ?? client).get({ + url: '/file', + ...options, + ...params + }); +}; + +/** + * Get file status + */ +export const fileStatus = (options?: Options) => (options?.client ?? client).get({ url: '/file/status', ...options }); + +/** + * Write a log entry to the server logs + */ +export const appLog = (parameters?: { + service?: string; + level?: 'debug' | 'info' | 'error' | 'warn'; + message?: string; + extra?: { + [key: string]: unknown; + }; +}, options?: Options) => { + const params = buildClientParams([parameters], [{ args: [ + { in: 'body', key: 'service' }, + { in: 'body', key: 'level' }, + { in: 'body', key: 'message' }, + { in: 'body', key: 'extra' } + ] }]); + return (options?.client ?? client).post({ + url: '/log', + ...options, + ...params, + headers: { + 'Content-Type': 'application/json', + ...options?.headers, + ...params.headers + } + }); +}; + +/** + * List all agents + */ +export const appAgents = (options?: Options) => (options?.client ?? client).get({ url: '/agent', ...options }); + +/** + * Append prompt to the TUI + */ +export const tuiAppendPrompt = (parameters?: { + text?: string; +}, options?: Options) => { + const params = buildClientParams([parameters], [{ args: [{ in: 'body', key: 'text' }] }]); + return (options?.client ?? client).post({ + url: '/tui/append-prompt', + ...options, + ...params, + headers: { + 'Content-Type': 'application/json', + ...options?.headers, + ...params.headers + } + }); +}; + +/** + * Open the help dialog + */ +export const tuiOpenHelp = (options?: Options) => (options?.client ?? client).post({ url: '/tui/open-help', ...options }); + +/** + * Open the session dialog + */ +export const tuiOpenSessions = (options?: Options) => (options?.client ?? client).post({ url: '/tui/open-sessions', ...options }); + +/** + * Open the theme dialog + */ +export const tuiOpenThemes = (options?: Options) => (options?.client ?? client).post({ url: '/tui/open-themes', ...options }); + +/** + * Open the model dialog + */ +export const tuiOpenModels = (options?: Options) => (options?.client ?? client).post({ url: '/tui/open-models', ...options }); + +/** + * Submit the prompt + */ +export const tuiSubmitPrompt = (options?: Options) => (options?.client ?? client).post({ url: '/tui/submit-prompt', ...options }); + +/** + * Clear the prompt + */ +export const tuiClearPrompt = (options?: Options) => (options?.client ?? client).post({ url: '/tui/clear-prompt', ...options }); + +/** + * Execute a TUI command (e.g. agent_cycle) + */ +export const tuiExecuteCommand = (parameters?: { + command?: string; +}, options?: Options) => { + const params = buildClientParams([parameters], [{ args: [{ in: 'body', key: 'command' }] }]); + return (options?.client ?? client).post({ + url: '/tui/execute-command', + ...options, + ...params, + headers: { + 'Content-Type': 'application/json', + ...options?.headers, + ...params.headers + } + }); +}; + +/** + * Show a toast notification in the TUI + */ +export const tuiShowToast = (parameters?: { + title?: string; + message?: string; + variant?: 'info' | 'success' | 'warning' | 'error'; +}, options?: Options) => { + const params = buildClientParams([parameters], [{ args: [ + { in: 'body', key: 'title' }, + { in: 'body', key: 'message' }, + { in: 'body', key: 'variant' } + ] }]); + return (options?.client ?? client).post({ + url: '/tui/show-toast', + ...options, + ...params, + headers: { + 'Content-Type': 'application/json', + ...options?.headers, + ...params.headers + } + }); +}; + +/** + * Set authentication credentials + */ +export const authSet = (parameters: { + id: string; + auth?: Auth; +}, options?: Options) => { + const params = buildClientParams([parameters], [{ args: [{ in: 'path', key: 'id' }, { key: 'auth', map: 'body' }] }]); + return (options?.client ?? client).put({ + url: '/auth/{id}', + ...options, + ...params, + headers: { + 'Content-Type': 'application/json', + ...options?.headers, + ...params.headers + } + }); +}; diff --git a/packages/openapi-ts-tests/sdks/__snapshots__/opencode/export-all/types.gen.ts b/packages/openapi-ts-tests/sdks/__snapshots__/opencode/export-all/types.gen.ts new file mode 100644 index 000000000..ccd376c4b --- /dev/null +++ b/packages/openapi-ts-tests/sdks/__snapshots__/opencode/export-all/types.gen.ts @@ -0,0 +1,1943 @@ +// This file is auto-generated by @hey-api/openapi-ts + +export type ClientOptions = { + baseUrl: `${string}://${string}` | (string & {}); +}; + +export type Event = ({ + type: 'installation.updated'; +} & EventInstallationUpdated) | ({ + type: 'lsp.client.diagnostics'; +} & EventLspClientDiagnostics) | ({ + type: 'message.updated'; +} & EventMessageUpdated) | ({ + type: 'message.removed'; +} & EventMessageRemoved) | ({ + type: 'message.part.updated'; +} & EventMessagePartUpdated) | ({ + type: 'message.part.removed'; +} & EventMessagePartRemoved) | ({ + type: 'storage.write'; +} & EventStorageWrite) | ({ + type: 'permission.updated'; +} & EventPermissionUpdated) | ({ + type: 'permission.replied'; +} & EventPermissionReplied) | ({ + type: 'file.edited'; +} & EventFileEdited) | ({ + type: 'session.updated'; +} & EventSessionUpdated) | ({ + type: 'session.deleted'; +} & EventSessionDeleted) | ({ + type: 'session.idle'; +} & EventSessionIdle) | ({ + type: 'session.error'; +} & EventSessionError) | ({ + type: 'server.connected'; +} & EventServerConnected) | ({ + type: 'file.watcher.updated'; +} & EventFileWatcherUpdated) | ({ + type: 'ide.installed'; +} & EventIdeInstalled); + +export type EventInstallationUpdated = { + type: 'installation.updated'; + properties: { + version: string; + }; +}; + +export type EventLspClientDiagnostics = { + type: 'lsp.client.diagnostics'; + properties: { + serverID: string; + path: string; + }; +}; + +export type EventMessageUpdated = { + type: 'message.updated'; + properties: { + info: Message; + }; +}; + +export type Message = ({ + role: 'user'; +} & UserMessage) | ({ + role: 'assistant'; +} & AssistantMessage); + +export type UserMessage = { + id: string; + sessionID: string; + role: 'user'; + time: { + created: number; + }; +}; + +export type AssistantMessage = { + id: string; + sessionID: string; + role: 'assistant'; + time: { + created: number; + completed?: number; + }; + error?: ({ + name: 'ProviderAuthError'; + } & ProviderAuthError) | ({ + name: 'UnknownError'; + } & UnknownError) | ({ + name: 'MessageOutputLengthError'; + } & MessageOutputLengthError) | ({ + name: 'MessageAbortedError'; + } & MessageAbortedError); + system: Array; + modelID: string; + providerID: string; + mode: string; + path: { + cwd: string; + root: string; + }; + summary?: boolean; + cost: number; + tokens: { + input: number; + output: number; + reasoning: number; + cache: { + read: number; + write: number; + }; + }; +}; + +export type ProviderAuthError = { + name: 'ProviderAuthError'; + data: { + providerID: string; + message: string; + }; +}; + +export type UnknownError = { + name: 'UnknownError'; + data: { + message: string; + }; +}; + +export type MessageOutputLengthError = { + name: 'MessageOutputLengthError'; + data: { + [key: string]: unknown; + }; +}; + +export type MessageAbortedError = { + name: 'MessageAbortedError'; + data: { + [key: string]: unknown; + }; +}; + +export type EventMessageRemoved = { + type: 'message.removed'; + properties: { + sessionID: string; + messageID: string; + }; +}; + +export type EventMessagePartUpdated = { + type: 'message.part.updated'; + properties: { + part: Part; + }; +}; + +export type Part = ({ + type: 'text'; +} & TextPart) | ({ + type: 'reasoning'; +} & ReasoningPart) | ({ + type: 'file'; +} & FilePart) | ({ + type: 'tool'; +} & ToolPart) | ({ + type: 'step-start'; +} & StepStartPart) | ({ + type: 'step-finish'; +} & StepFinishPart) | ({ + type: 'snapshot'; +} & SnapshotPart) | ({ + type: 'patch'; +} & PatchPart) | ({ + type: 'agent'; +} & AgentPart); + +export type TextPart = { + id: string; + sessionID: string; + messageID: string; + type: 'text'; + text: string; + synthetic?: boolean; + time?: { + start: number; + end?: number; + }; +}; + +export type ReasoningPart = { + id: string; + sessionID: string; + messageID: string; + type: 'reasoning'; + text: string; + metadata?: { + [key: string]: unknown; + }; + time: { + start: number; + end?: number; + }; +}; + +export type FilePart = { + id: string; + sessionID: string; + messageID: string; + type: 'file'; + mime: string; + filename?: string; + url: string; + source?: FilePartSource; +}; + +export type FilePartSource = ({ + type: 'file'; +} & FileSource) | ({ + type: 'symbol'; +} & SymbolSource); + +export type FileSource = { + text: FilePartSourceText; + type: 'file'; + path: string; +}; + +export type FilePartSourceText = { + value: string; + start: number; + end: number; +}; + +export type SymbolSource = { + text: FilePartSourceText; + type: 'symbol'; + path: string; + range: Range; + name: string; + kind: number; +}; + +export type Range = { + start: { + line: number; + character: number; + }; + end: { + line: number; + character: number; + }; +}; + +export type ToolPart = { + id: string; + sessionID: string; + messageID: string; + type: 'tool'; + callID: string; + tool: string; + state: ToolState; +}; + +export type ToolState = ({ + status: 'pending'; +} & ToolStatePending) | ({ + status: 'running'; +} & ToolStateRunning) | ({ + status: 'completed'; +} & ToolStateCompleted) | ({ + status: 'error'; +} & ToolStateError); + +export type ToolStatePending = { + status: 'pending'; +}; + +export type ToolStateRunning = { + status: 'running'; + input?: unknown; + title?: string; + metadata?: { + [key: string]: unknown; + }; + time: { + start: number; + }; +}; + +export type ToolStateCompleted = { + status: 'completed'; + input: { + [key: string]: unknown; + }; + output: string; + title: string; + metadata: { + [key: string]: unknown; + }; + time: { + start: number; + end: number; + }; +}; + +export type ToolStateError = { + status: 'error'; + input: { + [key: string]: unknown; + }; + error: string; + metadata?: { + [key: string]: unknown; + }; + time: { + start: number; + end: number; + }; +}; + +export type StepStartPart = { + id: string; + sessionID: string; + messageID: string; + type: 'step-start'; +}; + +export type StepFinishPart = { + id: string; + sessionID: string; + messageID: string; + type: 'step-finish'; + cost: number; + tokens: { + input: number; + output: number; + reasoning: number; + cache: { + read: number; + write: number; + }; + }; +}; + +export type SnapshotPart = { + id: string; + sessionID: string; + messageID: string; + type: 'snapshot'; + snapshot: string; +}; + +export type PatchPart = { + id: string; + sessionID: string; + messageID: string; + type: 'patch'; + hash: string; + files: Array; +}; + +export type AgentPart = { + id: string; + sessionID: string; + messageID: string; + type: 'agent'; + name: string; + source?: { + value: string; + start: number; + end: number; + }; +}; + +export type EventMessagePartRemoved = { + type: 'message.part.removed'; + properties: { + sessionID: string; + messageID: string; + partID: string; + }; +}; + +export type EventStorageWrite = { + type: 'storage.write'; + properties: { + key: string; + content?: unknown; + }; +}; + +export type EventPermissionUpdated = { + type: 'permission.updated'; + properties: Permission; +}; + +export type Permission = { + id: string; + type: string; + pattern?: string; + sessionID: string; + messageID: string; + callID?: string; + title: string; + metadata: { + [key: string]: unknown; + }; + time: { + created: number; + }; +}; + +export type EventPermissionReplied = { + type: 'permission.replied'; + properties: { + sessionID: string; + permissionID: string; + response: string; + }; +}; + +export type EventFileEdited = { + type: 'file.edited'; + properties: { + file: string; + }; +}; + +export type EventSessionUpdated = { + type: 'session.updated'; + properties: { + info: Session; + }; +}; + +export type Session = { + id: string; + parentID?: string; + share?: { + url: string; + }; + title: string; + version: string; + time: { + created: number; + updated: number; + }; + revert?: { + messageID: string; + partID?: string; + snapshot?: string; + diff?: string; + }; +}; + +export type EventSessionDeleted = { + type: 'session.deleted'; + properties: { + info: Session; + }; +}; + +export type EventSessionIdle = { + type: 'session.idle'; + properties: { + sessionID: string; + }; +}; + +export type EventSessionError = { + type: 'session.error'; + properties: { + sessionID?: string; + error?: ({ + name: 'ProviderAuthError'; + } & ProviderAuthError) | ({ + name: 'UnknownError'; + } & UnknownError) | ({ + name: 'MessageOutputLengthError'; + } & MessageOutputLengthError) | ({ + name: 'MessageAbortedError'; + } & MessageAbortedError); + }; +}; + +export type EventServerConnected = { + type: 'server.connected'; + properties: { + [key: string]: unknown; + }; +}; + +export type EventFileWatcherUpdated = { + type: 'file.watcher.updated'; + properties: { + file: string; + event: 'rename' | 'change'; + }; +}; + +export type EventIdeInstalled = { + type: 'ide.installed'; + properties: { + ide: string; + }; +}; + +export type App = { + hostname: string; + git: boolean; + path: { + config: string; + data: string; + root: string; + cwd: string; + state: string; + }; + time: { + initialized?: number; + }; +}; + +export type Config = { + /** + * JSON schema reference for configuration validation + */ + $schema?: string; + /** + * Theme name to use for the interface + */ + theme?: string; + /** + * Custom keybind configurations + */ + keybinds?: KeybindsConfig; + /** + * TUI specific settings + */ + tui?: { + /** + * TUI scroll speed + */ + scroll_speed: number; + }; + plugin?: Array; + snapshot?: boolean; + /** + * Control sharing behavior:'manual' allows manual sharing via commands, 'auto' enables automatic sharing, 'disabled' disables all sharing + */ + share?: 'manual' | 'auto' | 'disabled'; + /** + * @deprecated Use 'share' field instead. Share newly created sessions automatically + */ + autoshare?: boolean; + /** + * Automatically update to the latest version + */ + autoupdate?: boolean; + /** + * Disable providers that are loaded automatically + */ + disabled_providers?: Array; + /** + * Model to use in the format of provider/model, eg anthropic/claude-2 + */ + model?: string; + /** + * Small model to use for tasks like title generation in the format of provider/model + */ + small_model?: string; + /** + * Custom username to display in conversations instead of system username + */ + username?: string; + /** + * @deprecated Use `agent` field instead. + */ + mode?: { + build?: AgentConfig; + plan?: AgentConfig; + [key: string]: AgentConfig | undefined; + }; + /** + * Agent configuration, see https://opencode.ai/docs/agent + */ + agent?: { + plan?: AgentConfig; + build?: AgentConfig; + general?: AgentConfig; + [key: string]: AgentConfig | undefined; + }; + /** + * Custom provider configurations and model overrides + */ + provider?: { + [key: string]: { + api?: string; + name?: string; + env?: Array; + id?: string; + npm?: string; + models?: { + [key: string]: { + id?: string; + name?: string; + release_date?: string; + attachment?: boolean; + reasoning?: boolean; + temperature?: boolean; + tool_call?: boolean; + cost?: { + input: number; + output: number; + cache_read?: number; + cache_write?: number; + }; + limit?: { + context: number; + output: number; + }; + options?: { + [key: string]: unknown; + }; + }; + }; + options?: { + apiKey?: string; + baseURL?: string; + [key: string]: unknown | string | undefined; + }; + }; + }; + /** + * MCP (Model Context Protocol) server configurations + */ + mcp?: { + [key: string]: ({ + type: 'local'; + } & McpLocalConfig) | ({ + type: 'remote'; + } & McpRemoteConfig); + }; + formatter?: { + [key: string]: { + disabled?: boolean; + command?: Array; + environment?: { + [key: string]: string; + }; + extensions?: Array; + }; + }; + lsp?: { + [key: string]: { + disabled: true; + } | { + command: Array; + extensions?: Array; + disabled?: boolean; + env?: { + [key: string]: string; + }; + initialization?: { + [key: string]: unknown; + }; + }; + }; + /** + * Additional instruction files or patterns to include + */ + instructions?: Array; + /** + * @deprecated Always uses stretch layout. + */ + layout?: LayoutConfig; + permission?: { + edit?: 'ask' | 'allow' | 'deny'; + bash?: 'ask' | 'allow' | 'deny' | { + [key: string]: 'ask' | 'allow' | 'deny'; + }; + webfetch?: 'ask' | 'allow' | 'deny'; + }; + tools?: { + [key: string]: boolean; + }; + experimental?: { + hook?: { + file_edited?: { + [key: string]: Array<{ + command: Array; + environment?: { + [key: string]: string; + }; + }>; + }; + session_completed?: Array<{ + command: Array; + environment?: { + [key: string]: string; + }; + }>; + }; + }; +}; + +export type KeybindsConfig = { + /** + * Leader key for keybind combinations + */ + leader: string; + /** + * Show help dialog + */ + app_help: string; + /** + * Exit the application + */ + app_exit: string; + /** + * Open external editor + */ + editor_open: string; + /** + * List available themes + */ + theme_list: string; + /** + * Create/update AGENTS.md + */ + project_init: string; + /** + * Toggle tool details + */ + tool_details: string; + /** + * Toggle thinking blocks + */ + thinking_blocks: string; + /** + * Export session to editor + */ + session_export: string; + /** + * Create a new session + */ + session_new: string; + /** + * List all sessions + */ + session_list: string; + /** + * Show session timeline + */ + session_timeline: string; + /** + * Share current session + */ + session_share: string; + /** + * Unshare current session + */ + session_unshare: string; + /** + * Interrupt current session + */ + session_interrupt: string; + /** + * Compact the session + */ + session_compact: string; + /** + * Cycle to next child session + */ + session_child_cycle: string; + /** + * Cycle to previous child session + */ + session_child_cycle_reverse: string; + /** + * Scroll messages up by one page + */ + messages_page_up: string; + /** + * Scroll messages down by one page + */ + messages_page_down: string; + /** + * Scroll messages up by half page + */ + messages_half_page_up: string; + /** + * Scroll messages down by half page + */ + messages_half_page_down: string; + /** + * Navigate to first message + */ + messages_first: string; + /** + * Navigate to last message + */ + messages_last: string; + /** + * Copy message + */ + messages_copy: string; + /** + * Undo message + */ + messages_undo: string; + /** + * Redo message + */ + messages_redo: string; + /** + * List available models + */ + model_list: string; + /** + * Next recent model + */ + model_cycle_recent: string; + /** + * Previous recent model + */ + model_cycle_recent_reverse: string; + /** + * List agents + */ + agent_list: string; + /** + * Next agent + */ + agent_cycle: string; + /** + * Previous agent + */ + agent_cycle_reverse: string; + /** + * Clear input field + */ + input_clear: string; + /** + * Paste from clipboard + */ + input_paste: string; + /** + * Submit input + */ + input_submit: string; + /** + * Insert newline in input + */ + input_newline: string; + /** + * @deprecated use agent_cycle. Next mode + */ + switch_mode: string; + /** + * @deprecated use agent_cycle_reverse. Previous mode + */ + switch_mode_reverse: string; + /** + * @deprecated use agent_cycle. Next agent + */ + switch_agent: string; + /** + * @deprecated use agent_cycle_reverse. Previous agent + */ + switch_agent_reverse: string; + /** + * @deprecated Currently not available. List files + */ + file_list: string; + /** + * @deprecated Close file + */ + file_close: string; + /** + * @deprecated Search file + */ + file_search: string; + /** + * @deprecated Split/unified diff + */ + file_diff_toggle: string; + /** + * @deprecated Navigate to previous message + */ + messages_previous: string; + /** + * @deprecated Navigate to next message + */ + messages_next: string; + /** + * @deprecated Toggle layout + */ + messages_layout_toggle: string; + /** + * @deprecated use messages_undo. Revert message + */ + messages_revert: string; +}; + +export type AgentConfig = { + model?: string; + temperature?: number; + top_p?: number; + prompt?: string; + tools?: { + [key: string]: boolean; + }; + disable?: boolean; + /** + * Description of when to use the agent + */ + description?: string; + mode?: 'subagent' | 'primary' | 'all'; + permission?: { + edit?: 'ask' | 'allow' | 'deny'; + bash?: 'ask' | 'allow' | 'deny' | { + [key: string]: 'ask' | 'allow' | 'deny'; + }; + webfetch?: 'ask' | 'allow' | 'deny'; + }; + [key: string]: unknown | string | number | { + [key: string]: boolean; + } | boolean | 'subagent' | 'primary' | 'all' | { + edit?: 'ask' | 'allow' | 'deny'; + bash?: 'ask' | 'allow' | 'deny' | { + [key: string]: 'ask' | 'allow' | 'deny'; + }; + webfetch?: 'ask' | 'allow' | 'deny'; + } | undefined; +}; + +export type Provider = { + api?: string; + name: string; + env: Array; + id: string; + npm?: string; + models: { + [key: string]: Model; + }; +}; + +export type Model = { + id: string; + name: string; + release_date: string; + attachment: boolean; + reasoning: boolean; + temperature: boolean; + tool_call: boolean; + cost: { + input: number; + output: number; + cache_read?: number; + cache_write?: number; + }; + limit: { + context: number; + output: number; + }; + options: { + [key: string]: unknown; + }; +}; + +export type McpLocalConfig = { + /** + * Type of MCP server connection + */ + type: 'local'; + /** + * Command and arguments to run the MCP server + */ + command: Array; + /** + * Environment variables to set when running the MCP server + */ + environment?: { + [key: string]: string; + }; + /** + * Enable or disable the MCP server on startup + */ + enabled?: boolean; +}; + +export type McpRemoteConfig = { + /** + * Type of MCP server connection + */ + type: 'remote'; + /** + * URL of the remote MCP server + */ + url: string; + /** + * Enable or disable the MCP server on startup + */ + enabled?: boolean; + /** + * Headers to send with the request + */ + headers?: { + [key: string]: string; + }; +}; + +export type LayoutConfig = 'auto' | 'stretch'; + +export type Error = { + data: { + [key: string]: unknown; + }; +}; + +export type TextPartInput = { + id?: string; + type: 'text'; + text: string; + synthetic?: boolean; + time?: { + start: number; + end?: number; + }; +}; + +export type FilePartInput = { + id?: string; + type: 'file'; + mime: string; + filename?: string; + url: string; + source?: FilePartSource; +}; + +export type AgentPartInput = { + id?: string; + type: 'agent'; + name: string; + source?: { + value: string; + start: number; + end: number; + }; +}; + +export type Symbol = { + name: string; + kind: number; + location: { + uri: string; + range: Range; + }; +}; + +export type File = { + path: string; + added: number; + removed: number; + status: 'added' | 'deleted' | 'modified'; +}; + +export type Agent = { + name: string; + description?: string; + mode: 'subagent' | 'primary' | 'all'; + builtIn: boolean; + topP?: number; + temperature?: number; + permission: { + edit: 'ask' | 'allow' | 'deny'; + bash: { + [key: string]: 'ask' | 'allow' | 'deny'; + }; + webfetch?: 'ask' | 'allow' | 'deny'; + }; + model?: { + modelID: string; + providerID: string; + }; + prompt?: string; + tools: { + [key: string]: boolean; + }; + options: { + [key: string]: unknown; + }; +}; + +export type Auth = ({ + type: 'oauth'; +} & OAuth) | ({ + type: 'api'; +} & ApiAuth) | ({ + type: 'wellknown'; +} & WellKnownAuth); + +export type OAuth = { + type: 'oauth'; + refresh: string; + access: string; + expires: number; +}; + +export type ApiAuth = { + type: 'api'; + key: string; +}; + +export type WellKnownAuth = { + type: 'wellknown'; + key: string; + token: string; +}; + +export type EventSubscribeData = { + body?: never; + path?: never; + query?: never; + url: '/event'; +}; + +export type EventSubscribeResponses = { + /** + * Event stream + */ + 200: Event; +}; + +export type EventSubscribeResponse = EventSubscribeResponses[keyof EventSubscribeResponses]; + +export type AppGetData = { + body?: never; + path?: never; + query?: never; + url: '/app'; +}; + +export type AppGetResponses = { + /** + * 200 + */ + 200: App; +}; + +export type AppGetResponse = AppGetResponses[keyof AppGetResponses]; + +export type AppInitData = { + body?: never; + path?: never; + query?: never; + url: '/app/init'; +}; + +export type AppInitResponses = { + /** + * Initialize the app + */ + 200: boolean; +}; + +export type AppInitResponse = AppInitResponses[keyof AppInitResponses]; + +export type ConfigGetData = { + body?: never; + path?: never; + query?: never; + url: '/config'; +}; + +export type ConfigGetResponses = { + /** + * Get config info + */ + 200: Config; +}; + +export type ConfigGetResponse = ConfigGetResponses[keyof ConfigGetResponses]; + +export type SessionListData = { + body?: never; + path?: never; + query?: never; + url: '/session'; +}; + +export type SessionListResponses = { + /** + * List of sessions + */ + 200: Array; +}; + +export type SessionListResponse = SessionListResponses[keyof SessionListResponses]; + +export type SessionCreateData = { + body?: { + parentID?: string; + title?: string; + }; + path?: never; + query?: never; + url: '/session'; +}; + +export type SessionCreateErrors = { + /** + * Bad request + */ + 400: Error; +}; + +export type SessionCreateError = SessionCreateErrors[keyof SessionCreateErrors]; + +export type SessionCreateResponses = { + /** + * Successfully created session + */ + 200: Session; +}; + +export type SessionCreateResponse = SessionCreateResponses[keyof SessionCreateResponses]; + +export type SessionDeleteData = { + body?: never; + path: { + id: string; + }; + query?: never; + url: '/session/{id}'; +}; + +export type SessionDeleteResponses = { + /** + * Successfully deleted session + */ + 200: boolean; +}; + +export type SessionDeleteResponse = SessionDeleteResponses[keyof SessionDeleteResponses]; + +export type SessionGetData = { + body?: never; + path: { + id: string; + }; + query?: never; + url: '/session/{id}'; +}; + +export type SessionGetResponses = { + /** + * Get session + */ + 200: Session; +}; + +export type SessionGetResponse = SessionGetResponses[keyof SessionGetResponses]; + +export type SessionUpdateData = { + body?: { + title?: string; + }; + path: { + id: string; + }; + query?: never; + url: '/session/{id}'; +}; + +export type SessionUpdateResponses = { + /** + * Successfully updated session + */ + 200: Session; +}; + +export type SessionUpdateResponse = SessionUpdateResponses[keyof SessionUpdateResponses]; + +export type SessionChildrenData = { + body?: never; + path: { + id: string; + }; + query?: never; + url: '/session/{id}/children'; +}; + +export type SessionChildrenResponses = { + /** + * List of children + */ + 200: Array; +}; + +export type SessionChildrenResponse = SessionChildrenResponses[keyof SessionChildrenResponses]; + +export type SessionInitData = { + body?: { + messageID: string; + providerID: string; + modelID: string; + }; + path: { + /** + * Session ID + */ + id: string; + }; + query?: never; + url: '/session/{id}/init'; +}; + +export type SessionInitResponses = { + /** + * 200 + */ + 200: boolean; +}; + +export type SessionInitResponse = SessionInitResponses[keyof SessionInitResponses]; + +export type SessionAbortData = { + body?: never; + path: { + id: string; + }; + query?: never; + url: '/session/{id}/abort'; +}; + +export type SessionAbortResponses = { + /** + * Aborted session + */ + 200: boolean; +}; + +export type SessionAbortResponse = SessionAbortResponses[keyof SessionAbortResponses]; + +export type SessionUnshareData = { + body?: never; + path: { + id: string; + }; + query?: never; + url: '/session/{id}/share'; +}; + +export type SessionUnshareResponses = { + /** + * Successfully unshared session + */ + 200: Session; +}; + +export type SessionUnshareResponse = SessionUnshareResponses[keyof SessionUnshareResponses]; + +export type SessionShareData = { + body?: never; + path: { + id: string; + }; + query?: never; + url: '/session/{id}/share'; +}; + +export type SessionShareResponses = { + /** + * Successfully shared session + */ + 200: Session; +}; + +export type SessionShareResponse = SessionShareResponses[keyof SessionShareResponses]; + +export type SessionSummarizeData = { + body?: { + providerID: string; + modelID: string; + }; + path: { + /** + * Session ID + */ + id: string; + }; + query?: never; + url: '/session/{id}/summarize'; +}; + +export type SessionSummarizeResponses = { + /** + * Summarized session + */ + 200: boolean; +}; + +export type SessionSummarizeResponse = SessionSummarizeResponses[keyof SessionSummarizeResponses]; + +export type SessionMessagesData = { + body?: never; + path: { + /** + * Session ID + */ + id: string; + }; + query?: never; + url: '/session/{id}/message'; +}; + +export type SessionMessagesResponses = { + /** + * List of messages + */ + 200: Array<{ + info: Message; + parts: Array; + }>; +}; + +export type SessionMessagesResponse = SessionMessagesResponses[keyof SessionMessagesResponses]; + +export type SessionChatData = { + body?: { + messageID?: string; + providerID: string; + modelID: string; + agent?: string; + system?: string; + tools?: { + [key: string]: boolean; + }; + parts: Array<({ + type: 'text'; + } & TextPartInput) | ({ + type: 'file'; + } & FilePartInput) | ({ + type: 'agent'; + } & AgentPartInput)>; + }; + path: { + /** + * Session ID + */ + id: string; + }; + query?: never; + url: '/session/{id}/message'; +}; + +export type SessionChatResponses = { + /** + * Created message + */ + 200: { + info: AssistantMessage; + parts: Array; + }; +}; + +export type SessionChatResponse = SessionChatResponses[keyof SessionChatResponses]; + +export type SessionMessageData = { + body?: never; + path: { + /** + * Session ID + */ + id: string; + /** + * Message ID + */ + messageID: string; + }; + query?: never; + url: '/session/{id}/message/{messageID}'; +}; + +export type SessionMessageResponses = { + /** + * Message + */ + 200: { + info: Message; + parts: Array; + }; +}; + +export type SessionMessageResponse = SessionMessageResponses[keyof SessionMessageResponses]; + +export type SessionShellData = { + body?: { + agent: string; + command: string; + }; + path: { + /** + * Session ID + */ + id: string; + }; + query?: never; + url: '/session/{id}/shell'; +}; + +export type SessionShellResponses = { + /** + * Created message + */ + 200: AssistantMessage; +}; + +export type SessionShellResponse = SessionShellResponses[keyof SessionShellResponses]; + +export type SessionRevertData = { + body?: { + messageID: string; + partID?: string; + }; + path: { + id: string; + }; + query?: never; + url: '/session/{id}/revert'; +}; + +export type SessionRevertResponses = { + /** + * Updated session + */ + 200: Session; +}; + +export type SessionRevertResponse = SessionRevertResponses[keyof SessionRevertResponses]; + +export type SessionUnrevertData = { + body?: never; + path: { + id: string; + }; + query?: never; + url: '/session/{id}/unrevert'; +}; + +export type SessionUnrevertResponses = { + /** + * Updated session + */ + 200: Session; +}; + +export type SessionUnrevertResponse = SessionUnrevertResponses[keyof SessionUnrevertResponses]; + +export type PostSessionByIdPermissionsByPermissionIdData = { + body?: { + response: 'once' | 'always' | 'reject'; + }; + path: { + id: string; + permissionID: string; + }; + query?: never; + url: '/session/{id}/permissions/{permissionID}'; +}; + +export type PostSessionByIdPermissionsByPermissionIdResponses = { + /** + * Permission processed successfully + */ + 200: boolean; +}; + +export type PostSessionByIdPermissionsByPermissionIdResponse = PostSessionByIdPermissionsByPermissionIdResponses[keyof PostSessionByIdPermissionsByPermissionIdResponses]; + +export type ConfigProvidersData = { + body?: never; + path?: never; + query?: never; + url: '/config/providers'; +}; + +export type ConfigProvidersResponses = { + /** + * List of providers + */ + 200: { + providers: Array; + default: { + [key: string]: string; + }; + }; +}; + +export type ConfigProvidersResponse = ConfigProvidersResponses[keyof ConfigProvidersResponses]; + +export type FindTextData = { + body?: never; + path?: never; + query: { + pattern: string; + }; + url: '/find'; +}; + +export type FindTextResponses = { + /** + * Matches + */ + 200: Array<{ + path: { + text: string; + }; + lines: { + text: string; + }; + line_number: number; + absolute_offset: number; + submatches: Array<{ + match: { + text: string; + }; + start: number; + end: number; + }>; + }>; +}; + +export type FindTextResponse = FindTextResponses[keyof FindTextResponses]; + +export type FindFilesData = { + body?: never; + path?: never; + query: { + query: string; + }; + url: '/find/file'; +}; + +export type FindFilesResponses = { + /** + * File paths + */ + 200: Array; +}; + +export type FindFilesResponse = FindFilesResponses[keyof FindFilesResponses]; + +export type FindSymbolsData = { + body?: never; + path?: never; + query: { + query: string; + }; + url: '/find/symbol'; +}; + +export type FindSymbolsResponses = { + /** + * Symbols + */ + 200: Array; +}; + +export type FindSymbolsResponse = FindSymbolsResponses[keyof FindSymbolsResponses]; + +export type FileReadData = { + body?: never; + path?: never; + query: { + path: string; + }; + url: '/file'; +}; + +export type FileReadResponses = { + /** + * File content + */ + 200: { + type: 'raw' | 'patch'; + content: string; + }; +}; + +export type FileReadResponse = FileReadResponses[keyof FileReadResponses]; + +export type FileStatusData = { + body?: never; + path?: never; + query?: never; + url: '/file/status'; +}; + +export type FileStatusResponses = { + /** + * File status + */ + 200: Array; +}; + +export type FileStatusResponse = FileStatusResponses[keyof FileStatusResponses]; + +export type AppLogData = { + body?: { + /** + * Service name for the log entry + */ + service: string; + /** + * Log level + */ + level: 'debug' | 'info' | 'error' | 'warn'; + /** + * Log message + */ + message: string; + /** + * Additional metadata for the log entry + */ + extra?: { + [key: string]: unknown; + }; + }; + path?: never; + query?: never; + url: '/log'; +}; + +export type AppLogResponses = { + /** + * Log entry written successfully + */ + 200: boolean; +}; + +export type AppLogResponse = AppLogResponses[keyof AppLogResponses]; + +export type AppAgentsData = { + body?: never; + path?: never; + query?: never; + url: '/agent'; +}; + +export type AppAgentsResponses = { + /** + * List of agents + */ + 200: Array; +}; + +export type AppAgentsResponse = AppAgentsResponses[keyof AppAgentsResponses]; + +export type TuiAppendPromptData = { + body?: { + text: string; + }; + path?: never; + query?: never; + url: '/tui/append-prompt'; +}; + +export type TuiAppendPromptResponses = { + /** + * Prompt processed successfully + */ + 200: boolean; +}; + +export type TuiAppendPromptResponse = TuiAppendPromptResponses[keyof TuiAppendPromptResponses]; + +export type TuiOpenHelpData = { + body?: never; + path?: never; + query?: never; + url: '/tui/open-help'; +}; + +export type TuiOpenHelpResponses = { + /** + * Help dialog opened successfully + */ + 200: boolean; +}; + +export type TuiOpenHelpResponse = TuiOpenHelpResponses[keyof TuiOpenHelpResponses]; + +export type TuiOpenSessionsData = { + body?: never; + path?: never; + query?: never; + url: '/tui/open-sessions'; +}; + +export type TuiOpenSessionsResponses = { + /** + * Session dialog opened successfully + */ + 200: boolean; +}; + +export type TuiOpenSessionsResponse = TuiOpenSessionsResponses[keyof TuiOpenSessionsResponses]; + +export type TuiOpenThemesData = { + body?: never; + path?: never; + query?: never; + url: '/tui/open-themes'; +}; + +export type TuiOpenThemesResponses = { + /** + * Theme dialog opened successfully + */ + 200: boolean; +}; + +export type TuiOpenThemesResponse = TuiOpenThemesResponses[keyof TuiOpenThemesResponses]; + +export type TuiOpenModelsData = { + body?: never; + path?: never; + query?: never; + url: '/tui/open-models'; +}; + +export type TuiOpenModelsResponses = { + /** + * Model dialog opened successfully + */ + 200: boolean; +}; + +export type TuiOpenModelsResponse = TuiOpenModelsResponses[keyof TuiOpenModelsResponses]; + +export type TuiSubmitPromptData = { + body?: never; + path?: never; + query?: never; + url: '/tui/submit-prompt'; +}; + +export type TuiSubmitPromptResponses = { + /** + * Prompt submitted successfully + */ + 200: boolean; +}; + +export type TuiSubmitPromptResponse = TuiSubmitPromptResponses[keyof TuiSubmitPromptResponses]; + +export type TuiClearPromptData = { + body?: never; + path?: never; + query?: never; + url: '/tui/clear-prompt'; +}; + +export type TuiClearPromptResponses = { + /** + * Prompt cleared successfully + */ + 200: boolean; +}; + +export type TuiClearPromptResponse = TuiClearPromptResponses[keyof TuiClearPromptResponses]; + +export type TuiExecuteCommandData = { + body?: { + command: string; + }; + path?: never; + query?: never; + url: '/tui/execute-command'; +}; + +export type TuiExecuteCommandResponses = { + /** + * Command executed successfully + */ + 200: boolean; +}; + +export type TuiExecuteCommandResponse = TuiExecuteCommandResponses[keyof TuiExecuteCommandResponses]; + +export type TuiShowToastData = { + body?: { + title?: string; + message: string; + variant: 'info' | 'success' | 'warning' | 'error'; + }; + path?: never; + query?: never; + url: '/tui/show-toast'; +}; + +export type TuiShowToastResponses = { + /** + * Toast notification shown successfully + */ + 200: boolean; +}; + +export type TuiShowToastResponse = TuiShowToastResponses[keyof TuiShowToastResponses]; + +export type AuthSetData = { + body?: Auth; + path: { + id: string; + }; + query?: never; + url: '/auth/{id}'; +}; + +export type AuthSetErrors = { + /** + * Bad request + */ + 400: Error; +}; + +export type AuthSetError = AuthSetErrors[keyof AuthSetErrors]; + +export type AuthSetResponses = { + /** + * Successfully set authentication credentials + */ + 200: boolean; +}; + +export type AuthSetResponse = AuthSetResponses[keyof AuthSetResponses]; diff --git a/packages/openapi-ts-tests/sdks/test/opencode.test.ts b/packages/openapi-ts-tests/sdks/test/opencode.test.ts index 03196d1c5..a2ade526b 100644 --- a/packages/openapi-ts-tests/sdks/test/opencode.test.ts +++ b/packages/openapi-ts-tests/sdks/test/opencode.test.ts @@ -24,6 +24,22 @@ describe(`SDK: ${namespace}`, () => { }); const scenarios = [ + { + config: createConfig({ + input: specPath, + output: { + path: 'export-all', + preferExportAll: true, + }, + plugins: [ + { + name: '@hey-api/sdk', + paramsStructure: 'flat', + }, + ], + }), + description: 'export all', + }, { config: createConfig({ input: specPath, diff --git a/packages/openapi-ts/src/parser/types/hooks.d.ts b/packages/openapi-ts/src/parser/types/hooks.d.ts index 2095b35cf..80453855e 100644 --- a/packages/openapi-ts/src/parser/types/hooks.d.ts +++ b/packages/openapi-ts/src/parser/types/hooks.d.ts @@ -1,4 +1,4 @@ -import type { Symbol, SymbolIn } from '@hey-api/codegen-core'; +import type { Node, Symbol, SymbolIn } from '@hey-api/codegen-core'; import type { IROperationObject } from '~/ir/types'; import type { PluginInstance } from '~/plugins/shared/utils/instance'; @@ -8,6 +8,34 @@ export type Hooks = { * Event hooks. */ events?: { + /** + * Triggered after adding or updating a node. + * + * You can use this to perform actions after a node is added or updated. + * + * @param args Arguments object. + * @returns void + */ + 'node:set:after'?: (args: { + /** The node added or updated. */ + node: Node | null; + /** Plugin that added or updated the node. */ + plugin: PluginInstance; + }) => void; + /** + * Triggered before adding or updating a node. + * + * You can use this to modify the node before it's added or updated. + * + * @param args Arguments object. + * @returns void + */ + 'node:set:before'?: (args: { + /** The node to be added or updated. */ + node: Node | null; + /** Plugin adding or updating the node. */ + plugin: PluginInstance; + }) => void; /** * Triggered after executing a plugin handler. * @@ -56,38 +84,6 @@ export type Hooks = { /** Symbol to register. */ symbol: SymbolIn; }) => void; - /** - * Triggered after setting a symbol value. - * - * You can use this to perform actions after a symbol's value is set. - * - * @param args Arguments object. - * @returns void - */ - 'symbol:setValue:after'?: (args: { - /** Plugin that set the symbol value. */ - plugin: PluginInstance; - /** The symbol. */ - symbol: Symbol; - /** The value that was set. */ - value: unknown; - }) => void; - /** - * Triggered before setting a symbol value. - * - * You can use this to modify the value before it's set. - * - * @param args Arguments object. - * @returns void - */ - 'symbol:setValue:before'?: (args: { - /** Plugin setting the symbol value. */ - plugin: PluginInstance; - /** The symbol. */ - symbol: Symbol; - /** The value to set. */ - value: unknown; - }) => void; }; /** * Hooks specifically for overriding operations behavior. diff --git a/packages/openapi-ts/src/plugins/shared/utils/instance.ts b/packages/openapi-ts/src/plugins/shared/utils/instance.ts index de15a884b..66f7e8b69 100644 --- a/packages/openapi-ts/src/plugins/shared/utils/instance.ts +++ b/packages/openapi-ts/src/plugins/shared/utils/instance.ts @@ -107,13 +107,24 @@ export class PluginInstance { } addNode(node: Node | null): number { - return this.gen.nodes.add(node); - } - removeNode(index: number): void { - return this.gen.nodes.remove(index); + for (const hook of this.eventHooks['node:set:before']) { + hook({ node, plugin: this }); + } + const index = this.gen.nodes.add(node); + for (const hook of this.eventHooks['node:set:after']) { + hook({ node, plugin: this }); + } + return index; } updateNode(index: number, node: Node | null): void { - return this.gen.nodes.update(index, node); + for (const hook of this.eventHooks['node:set:before']) { + hook({ node, plugin: this }); + } + const result = this.gen.nodes.update(index, node); + for (const hook of this.eventHooks['node:set:after']) { + hook({ node, plugin: this }); + } + return result; } /** @@ -366,12 +377,12 @@ export class PluginInstance { private buildEventHooks(): EventHooks { const result: EventHooks = { + 'node:set:after': [], + 'node:set:before': [], 'plugin:handler:after': [], 'plugin:handler:before': [], 'symbol:register:after': [], 'symbol:register:before': [], - 'symbol:setValue:after': [], - 'symbol:setValue:before': [], }; const scopes = [ this.config['~hooks']?.events,