@serkonda7/unifi-api 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (31) hide show
  1. package/README.md +149 -2
  2. package/dist/generated/client/client.gen.d.ts +2 -0
  3. package/dist/generated/client/index.d.ts +10 -0
  4. package/dist/generated/client/types.gen.d.ts +120 -0
  5. package/dist/generated/client/utils.gen.d.ts +37 -0
  6. package/dist/generated/client.gen.d.ts +12 -0
  7. package/dist/generated/core/auth.gen.d.ts +25 -0
  8. package/dist/generated/core/bodySerializer.gen.d.ts +25 -0
  9. package/dist/generated/core/params.gen.d.ts +43 -0
  10. package/dist/generated/core/pathSerializer.gen.d.ts +33 -0
  11. package/dist/generated/core/queryKeySerializer.gen.d.ts +18 -0
  12. package/dist/generated/core/serverSentEvents.gen.d.ts +71 -0
  13. package/dist/generated/core/types.gen.d.ts +83 -0
  14. package/dist/generated/core/utils.gen.d.ts +19 -0
  15. package/dist/generated/index.d.ts +2 -0
  16. package/dist/generated/sdk.gen.d.ts +99 -0
  17. package/dist/generated/types.gen.d.ts +2718 -0
  18. package/dist/index.d.ts +6 -0
  19. package/dist/index.js +6 -0
  20. package/dist/shared/client.d.ts +26 -0
  21. package/dist/shared/errors.d.ts +47 -0
  22. package/dist/shared/pagination.d.ts +18 -0
  23. package/dist/site-manager/client.d.ts +32 -0
  24. package/dist/site-manager/index.d.ts +64 -0
  25. package/dist/site-manager/resources/connector.d.ts +107 -0
  26. package/dist/site-manager/resources/devices.d.ts +36 -0
  27. package/dist/site-manager/resources/hosts.d.ts +41 -0
  28. package/dist/site-manager/resources/ispMetrics.d.ts +48 -0
  29. package/dist/site-manager/resources/sdWan.d.ts +27 -0
  30. package/dist/site-manager/resources/sites.d.ts +34 -0
  31. package/package.json +52 -4
package/README.md CHANGED
@@ -1,3 +1,150 @@
1
- # Temporary Holding Version
1
+ # unifi-api
2
+ [![CI][ci-badge]][ci-status]
3
+ [![npm version][npm-badge]][npm-link]
4
+ [![npm updated][npm-date-badge]][npm-link]
2
5
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
6
+ TypeScript client for the UniFi Site Manager API.
7
+
8
+
9
+ ## ℹ️ Disclaimer
10
+ This project is an _unofficial_ API client for the UniFi Site Manager API.
11
+
12
+ It is not affiliated with, endorsed by, or sponsored by Ubiquiti Inc. UniFi and related trademarks are the property of Ubiquiti Inc.
13
+
14
+ Use of this package requires a UniFi account and a Site Manager API key.
15
+
16
+ The authors provide this client as-is and make no guarantees regarding correctness, availability, compatibility, or future changes of the UniFi Site Manager API.
17
+
18
+
19
+ ## 📦 Installation
20
+ ```sh
21
+ bun install @serkonda7/unifi-api
22
+ ```
23
+
24
+
25
+ ## 🚀 Usage
26
+ Also check out the official UniFi Site Manager API docs: https://developer.ui.com/site-manager-api/
27
+
28
+ To get an API key, sign in at https://unifi.ui.com, open the API section, and create an API key. Personal API keys can only reach consoles owned by your account; organization API keys can reach all consoles in the organization.
29
+
30
+ Site Manager endpoints are rate limited — a client that exceeds its limit receives HTTP 429 with a `Retry-After` header.
31
+
32
+ ### Create the client
33
+ ```ts
34
+ import { createUnifiClient } from '@serkonda7/unifi-api'
35
+
36
+ const unifi = createUnifiClient({
37
+ apiKey: process.env.UNIFI_API_KEY!,
38
+ // baseUrl defaults to https://api.ui.com
39
+ })
40
+ ```
41
+
42
+ Each client owns an isolated instance, so auth can't leak between clients. Rotate the key later with `unifi.setApiKey(nextKey)`. `unifi.instance` exposes the underlying hey-api client (interceptors, raw SDK calls).
43
+
44
+ ### Make requests
45
+ ```ts
46
+ import { createUnifiClient, UnifiApiError } from '@serkonda7/unifi-api'
47
+
48
+ const unifi = createUnifiClient({ apiKey: process.env.UNIFI_API_KEY! })
49
+
50
+ try {
51
+ // GET /v1/hosts — follows `nextToken` pagination automatically
52
+ const hosts = await unifi.hosts.listAll()
53
+
54
+ // GET /v1/hosts/{id}
55
+ const hostId = hosts[0]?.id
56
+ if (hostId) {
57
+ const host = await unifi.hosts.get(hostId)
58
+
59
+ // GET /v1/devices, filtered by host
60
+ const devices = await unifi.devices.listAll({ hostIds: [hostId] })
61
+ }
62
+
63
+ // GET /v1/sites
64
+ for await (const site of unifi.sites.iterate()) {
65
+ console.log(site.siteId, site.hostId, site.isOwner)
66
+ }
67
+
68
+ // GET /v1/isp-metrics/{type}
69
+ const metrics = await unifi.ispMetrics.get('5m', { duration: '24h' })
70
+ } catch (error) {
71
+ if (error instanceof UnifiApiError) {
72
+ console.error(error.status, error.code, error.message, error.traceId, error.retryAfter)
73
+ } else {
74
+ throw error
75
+ }
76
+ }
77
+ ```
78
+
79
+ Methods return the response's `data` directly. List methods return `{ data, nextToken }` pages, `iterate()` is an async generator that follows pagination, and `listAll()` collects all pages. Non-2xx responses throw a `UnifiApiError` with the fields `status`, `code`, `message`, `traceId`, `retryAfter`, and `body`.
80
+
81
+ Available resources:
82
+
83
+ | Resource | Methods | Endpoint(s) |
84
+ | --- | --- | --- |
85
+ | `hosts` | `list`, `iterate`, `listAll`, `get` | `GET /v1/hosts`, `GET /v1/hosts/{id}` |
86
+ | `sites` | `list`, `iterate`, `listAll` | `GET /v1/sites` |
87
+ | `devices` | `list`, `iterate`, `listAll` | `GET /v1/devices` |
88
+ | `ispMetrics` | `get`, `query` | `GET /v1/isp-metrics/{type}`, `POST /v1/isp-metrics/{type}/query` |
89
+ | `sdWan` | `list`, `get`, `status` | `GET /v1/sd-wan-configs`, `GET /v1/sd-wan-configs/{id}`, `GET /v1/sd-wan-configs/{id}/status` |
90
+ | `connector` | `get`, `post`, `put`, `patch`, `delete`, `request`, `forConsole`, `network`, `protect` | `* /v1/connector/consoles/{id}/{path}` |
91
+
92
+ Full method reference (regenerated via `bun run docs`): [`docs/unifi-client.html`](./docs/unifi-client.html).
93
+
94
+
95
+ ## 🔌 Cloud connector
96
+ The connector proxies requests through api.ui.com to the local UniFi applications (Network, Protect, InnerSpace) running on a console. It requires console firmware ≥ 5.0.3 and is limited to 100 requests/minute per console, a 25 s timeout, and a 10 MB response body. The upstream response is passed through unchanged (it is not wrapped).
97
+
98
+ ```ts
99
+ const hostId = '900A6F00301100000000074A6BA90000000007A3387E0000000063EC9853:123456789'
100
+
101
+ // GET /v1/connector/consoles/{hostId}/network/integration/v1/sites
102
+ const network = unifi.connector.network(hostId)
103
+ const sites = await network.get<{ data: { id: string; name: string }[] }>('/v1/sites')
104
+
105
+ // GET /v1/connector/consoles/{hostId}/protect/integration/v1/meta/info
106
+ const info = await unifi.connector.protect(hostId).get('/v1/meta/info')
107
+
108
+ // Any other path, any method
109
+ await unifi.connector.post(hostId, `network/integration/v1/sites/${siteId}/...`, { /* body */ })
110
+ ```
111
+
112
+ See the Network API docs at https://developer.ui.com/network and the Protect API docs at https://developer.ui.com/protect.
113
+
114
+
115
+ ## 🧰 Generated SDK
116
+ The raw hey-api functions (`listHosts`, `getHostById`, `listSites`, `listDevices`, `getIspMetrics`, `queryIspMetrics`, `listSdWanConfigs`, `getSdWanConfigById`, `getSdWanConfigStatus`) are exported too. They return `{ data, error }` unions. Configure the shared singleton:
117
+
118
+ ```ts
119
+ import { client, listHosts } from '@serkonda7/unifi-api'
120
+
121
+ client.setConfig({ auth: process.env.UNIFI_API_KEY! })
122
+
123
+ const { data, error } = await listHosts({ query: { pageSize: '50' } })
124
+ ```
125
+
126
+ Note: the generated `connector*` functions cannot be used for real requests (the spec's wildcard path is not expanded) — use `unifi.connector` instead.
127
+
128
+
129
+ ## 🛠️ Development
130
+ - `bun install` — install dependencies
131
+ - `bun run generate` — regenerate `src/generated` from `openapi/site-manager-1.0.0.json`
132
+ - `bun run check` — type-check the project
133
+ - `bun run lint` — lint/format with Biome
134
+ - `bun test` — run the test suite
135
+ - `bun run build` — build the package
136
+ - `bun run docs` — generate the method reference
137
+
138
+
139
+ ## 📜 License
140
+ The UniFi Site Manager API and its specification are provided by Ubiquiti Inc. under their terms.
141
+
142
+ <!-- TODO: choose a license for this package -->
143
+
144
+
145
+ <!-- links -->
146
+ [ci-badge]: https://github.com/serkonda7/unifi-api/actions/workflows/ci.yml/badge.svg
147
+ [ci-status]: https://github.com/serkonda7/unifi-api/actions/workflows/ci.yml
148
+ [npm-badge]: https://nodei.co/npm/@serkonda7/unifi-api.png?style=shields&data=v&color=blue
149
+ [npm-date-badge]: https://nodei.co/npm/@serkonda7/unifi-api.png?style=shields&data=u,d&color=blue
150
+ [npm-link]: https://www.npmjs.com/package/@serkonda7/unifi-api
@@ -0,0 +1,2 @@
1
+ import type { Client, Config } from './types.gen';
2
+ export declare const createClient: (config?: Config) => Client;
@@ -0,0 +1,10 @@
1
+ export type { Auth } from '../core/auth.gen';
2
+ export type { QuerySerializerOptions } from '../core/bodySerializer.gen';
3
+ export { formDataBodySerializer, jsonBodySerializer, urlSearchParamsBodySerializer, } from '../core/bodySerializer.gen';
4
+ export { buildClientParams } from '../core/params.gen';
5
+ export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen';
6
+ export type { ServerSentEventsResult } from '../core/serverSentEvents.gen';
7
+ export type { ClientMeta } from '../core/types.gen';
8
+ export { createClient } from './client.gen';
9
+ export type { Client, ClientOptions, Config, CreateClientConfig, Options, RequestOptions, RequestResult, ResolvedRequestOptions, ResponseStyle, TDataShape, } from './types.gen';
10
+ export { createConfig, mergeHeaders } from './utils.gen';
@@ -0,0 +1,120 @@
1
+ import type { Auth } from '../core/auth.gen';
2
+ import type { ServerSentEventsOptions, ServerSentEventsResult } from '../core/serverSentEvents.gen';
3
+ import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen';
4
+ import type { Middleware } from './utils.gen';
5
+ export type ResponseStyle = 'data' | 'fields';
6
+ export interface Config<T extends ClientOptions = ClientOptions> extends Omit<RequestInit, 'body' | 'headers' | 'method'>, CoreConfig {
7
+ /**
8
+ * Base URL for all requests made by this client.
9
+ */
10
+ baseUrl?: T['baseUrl'];
11
+ /**
12
+ * Fetch API implementation. You can use this option to provide a custom
13
+ * fetch instance.
14
+ *
15
+ * @default globalThis.fetch
16
+ */
17
+ fetch?: typeof fetch;
18
+ /**
19
+ * Please don't use the Fetch client for Next.js applications. The `next`
20
+ * options won't have any effect.
21
+ *
22
+ * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead.
23
+ */
24
+ next?: never;
25
+ /**
26
+ * Return the response data parsed in a specified format. By default, `auto`
27
+ * will infer the appropriate method from the `Content-Type` response header.
28
+ * You can override this behavior with any of the {@link Body} methods.
29
+ * Select `stream` if you don't want to parse response data at all.
30
+ *
31
+ * @default 'auto'
32
+ */
33
+ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text';
34
+ /**
35
+ * Should we return only data or multiple fields (data, error, response, etc.)?
36
+ *
37
+ * @default 'fields'
38
+ */
39
+ responseStyle?: ResponseStyle;
40
+ /**
41
+ * Throw an error instead of returning it in the response?
42
+ *
43
+ * @default false
44
+ */
45
+ throwOnError?: T['throwOnError'];
46
+ }
47
+ export interface RequestOptions<TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string> extends Config<{
48
+ responseStyle: TResponseStyle;
49
+ throwOnError: ThrowOnError;
50
+ }>, Pick<ServerSentEventsOptions<TData>, 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay'> {
51
+ /**
52
+ * Any body that you want to add to your request.
53
+ *
54
+ * {@link https://developer.mozilla.org/docs/Web/API/fetch#body}
55
+ */
56
+ body?: unknown;
57
+ path?: Record<string, unknown>;
58
+ query?: Record<string, unknown>;
59
+ /**
60
+ * Security mechanism(s) to use for the request.
61
+ */
62
+ security?: ReadonlyArray<Auth>;
63
+ url: Url;
64
+ }
65
+ export interface ResolvedRequestOptions<TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string> extends RequestOptions<unknown, TResponseStyle, ThrowOnError, Url> {
66
+ headers: Headers;
67
+ serializedBody?: string;
68
+ }
69
+ export type RequestResult<TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields'> = ThrowOnError extends true ? Promise<TResponseStyle extends 'data' ? TData extends Record<string, unknown> ? TData[keyof TData] : TData : {
70
+ data: TData extends Record<string, unknown> ? TData[keyof TData] : TData;
71
+ request: Request;
72
+ response: Response;
73
+ }> : Promise<TResponseStyle extends 'data' ? (TData extends Record<string, unknown> ? TData[keyof TData] : TData) | undefined : ({
74
+ data: TData extends Record<string, unknown> ? TData[keyof TData] : TData;
75
+ error: undefined;
76
+ } | {
77
+ data: undefined;
78
+ error: TError extends Record<string, unknown> ? TError[keyof TError] : TError;
79
+ }) & {
80
+ /** request may be undefined, because error may be from building the request object itself */
81
+ request?: Request;
82
+ /** response may be undefined, because error may be from building the request object itself or from a network error */
83
+ response?: Response;
84
+ }>;
85
+ export interface ClientOptions {
86
+ baseUrl?: string;
87
+ responseStyle?: ResponseStyle;
88
+ throwOnError?: boolean;
89
+ }
90
+ type MethodFn = <TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields'>(options: Omit<RequestOptions<TData, TResponseStyle, ThrowOnError>, 'method'>) => RequestResult<TData, TError, ThrowOnError, TResponseStyle>;
91
+ type SseFn = <TData = unknown, _TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields'>(options: Omit<RequestOptions<never, TResponseStyle, ThrowOnError>, 'method'>) => Promise<ServerSentEventsResult<TData>>;
92
+ type RequestFn = <TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields'>(options: Omit<RequestOptions<TData, TResponseStyle, ThrowOnError>, 'method'> & Pick<Required<RequestOptions<TData, TResponseStyle, ThrowOnError>>, 'method'>) => RequestResult<TData, TError, ThrowOnError, TResponseStyle>;
93
+ type BuildUrlFn = <TData extends {
94
+ body?: unknown;
95
+ path?: Record<string, unknown>;
96
+ query?: Record<string, unknown>;
97
+ url: string;
98
+ }>(options: TData & Options<TData>) => string;
99
+ export type Client = CoreClient<RequestFn, Config, MethodFn, BuildUrlFn, SseFn> & {
100
+ interceptors: Middleware<Request, Response, unknown, ResolvedRequestOptions>;
101
+ };
102
+ /**
103
+ * The `createClientConfig()` function will be called on client initialization
104
+ * and the returned object will become the client's initial configuration.
105
+ *
106
+ * You may want to initialize your client this way instead of calling
107
+ * `setConfig()`. This is useful for example if you're using Next.js
108
+ * to ensure your client always has the correct values.
109
+ */
110
+ export type CreateClientConfig<T extends ClientOptions = ClientOptions> = (override?: Config<ClientOptions & T>) => Config<Required<ClientOptions> & T>;
111
+ export interface TDataShape {
112
+ body?: unknown;
113
+ headers?: unknown;
114
+ path?: unknown;
115
+ query?: unknown;
116
+ url: string;
117
+ }
118
+ type OmitKeys<T, K> = Pick<T, Exclude<keyof T, K>>;
119
+ export type Options<TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields'> = OmitKeys<RequestOptions<TResponse, TResponseStyle, ThrowOnError>, 'body' | 'path' | 'query' | 'url'> & ([TData] extends [never] ? unknown : Omit<TData, 'url'>);
120
+ export {};
@@ -0,0 +1,37 @@
1
+ import type { QuerySerializerOptions } from '../core/bodySerializer.gen';
2
+ import type { Client, ClientOptions, Config, RequestOptions } from './types.gen';
3
+ export declare const createQuerySerializer: <T = unknown>({ parameters, ...args }?: QuerySerializerOptions) => ((queryParams: T) => string);
4
+ /**
5
+ * Infers parseAs value from provided Content-Type header.
6
+ */
7
+ export declare const getParseAs: (contentType: string | null) => Exclude<Config['parseAs'], 'auto'>;
8
+ export declare function setAuthParams(options: Pick<RequestOptions, 'auth' | 'query' | 'security'> & {
9
+ headers: Headers;
10
+ }): Promise<void>;
11
+ export declare const buildUrl: Client['buildUrl'];
12
+ export declare const mergeConfigs: (a: Config, b: Config) => Config;
13
+ export declare const mergeHeaders: (...headers: Array<Required<Config>['headers'] | undefined>) => Headers;
14
+ type ErrInterceptor<Err, Res, Req, Options> = (error: Err,
15
+ /** response may be undefined due to a network error where no response object is produced */
16
+ response: Res | undefined,
17
+ /** request may be undefined, because error may be from building the request object itself */
18
+ request: Req | undefined, options: Options) => Err | Promise<Err>;
19
+ type ReqInterceptor<Req, Options> = (request: Req, options: Options) => Req | Promise<Req>;
20
+ type ResInterceptor<Res, Req, Options> = (response: Res, request: Req, options: Options) => Res | Promise<Res>;
21
+ declare class Interceptors<Interceptor> {
22
+ fns: Array<Interceptor | null>;
23
+ clear(): void;
24
+ eject(id: number | Interceptor): void;
25
+ exists(id: number | Interceptor): boolean;
26
+ getInterceptorIndex(id: number | Interceptor): number;
27
+ update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false;
28
+ use(fn: Interceptor): number;
29
+ }
30
+ export interface Middleware<Req, Res, Err, Options> {
31
+ error: Interceptors<ErrInterceptor<Err, Res, Req, Options>>;
32
+ request: Interceptors<ReqInterceptor<Req, Options>>;
33
+ response: Interceptors<ResInterceptor<Res, Req, Options>>;
34
+ }
35
+ export declare const createInterceptors: <Req, Res, Err, Options>() => Middleware<Req, Res, Err, Options>;
36
+ export declare const createConfig: <T extends ClientOptions = ClientOptions>(override?: Config<Omit<ClientOptions, keyof T> & T>) => Config<Omit<ClientOptions, keyof T> & T>;
37
+ export {};
@@ -0,0 +1,12 @@
1
+ import { type Client, type ClientOptions, type Config } from './client';
2
+ import type { ClientOptions as ClientOptions2 } from './types.gen';
3
+ /**
4
+ * The `createClientConfig()` function will be called on client initialization
5
+ * and the returned object will become the client's initial configuration.
6
+ *
7
+ * You may want to initialize your client this way instead of calling
8
+ * `setConfig()`. This is useful for example if you're using Next.js
9
+ * to ensure your client always has the correct values.
10
+ */
11
+ export type CreateClientConfig<T extends ClientOptions = ClientOptions2> = (override?: Config<ClientOptions & T>) => Config<Required<ClientOptions> & T>;
12
+ export declare const client: Client;
@@ -0,0 +1,25 @@
1
+ export type AuthToken = string | undefined;
2
+ export interface Auth {
3
+ /**
4
+ * Which part of the request do we use to send the auth?
5
+ *
6
+ * @default 'header'
7
+ */
8
+ in?: 'header' | 'query' | 'cookie';
9
+ /**
10
+ * A unique identifier for the security scheme.
11
+ *
12
+ * Defined only when there are multiple security schemes whose `Auth`
13
+ * shape would otherwise be identical.
14
+ */
15
+ key?: string;
16
+ /**
17
+ * Header or query parameter name.
18
+ *
19
+ * @default 'Authorization'
20
+ */
21
+ name?: string;
22
+ scheme?: 'basic' | 'bearer';
23
+ type: 'apiKey' | 'http';
24
+ }
25
+ export declare const getAuthToken: (auth: Auth, callback: ((auth: Auth) => Promise<AuthToken> | AuthToken) | AuthToken) => Promise<string | undefined>;
@@ -0,0 +1,25 @@
1
+ import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen';
2
+ export type QuerySerializer = (query: Record<string, unknown>) => string;
3
+ export type BodySerializer = (body: unknown) => unknown;
4
+ type QuerySerializerOptionsObject = {
5
+ allowReserved?: boolean;
6
+ array?: Partial<SerializerOptions<ArrayStyle>>;
7
+ object?: Partial<SerializerOptions<ObjectStyle>>;
8
+ };
9
+ export type QuerySerializerOptions = QuerySerializerOptionsObject & {
10
+ /**
11
+ * Per-parameter serialization overrides. When provided, these settings
12
+ * override the global array/object settings for specific parameter names.
13
+ */
14
+ parameters?: Record<string, QuerySerializerOptionsObject>;
15
+ };
16
+ export declare const formDataBodySerializer: {
17
+ bodySerializer: (body: unknown) => FormData;
18
+ };
19
+ export declare const jsonBodySerializer: {
20
+ bodySerializer: (body: unknown) => string;
21
+ };
22
+ export declare const urlSearchParamsBodySerializer: {
23
+ bodySerializer: (body: unknown) => string;
24
+ };
25
+ export {};
@@ -0,0 +1,43 @@
1
+ type Slot = 'body' | 'headers' | 'path' | 'query';
2
+ export type Field = {
3
+ in: Exclude<Slot, 'body'>;
4
+ /**
5
+ * Field name. This is the name we want the user to see and use.
6
+ */
7
+ key: string;
8
+ /**
9
+ * Field mapped name. This is the name we want to use in the request.
10
+ * If omitted, we use the same value as `key`.
11
+ */
12
+ map?: string;
13
+ } | {
14
+ in: Extract<Slot, 'body'>;
15
+ /**
16
+ * Key isn't required for bodies.
17
+ */
18
+ key?: string;
19
+ map?: string;
20
+ } | {
21
+ /**
22
+ * Field name. This is the name we want the user to see and use.
23
+ */
24
+ key: string;
25
+ /**
26
+ * Field mapped name. This is the name we want to use in the request.
27
+ * If `in` is omitted, `map` aliases `key` to the transport layer.
28
+ */
29
+ map: Slot;
30
+ };
31
+ export interface Fields {
32
+ allowExtra?: Partial<Record<Slot, boolean>>;
33
+ args?: ReadonlyArray<Field>;
34
+ }
35
+ export type FieldsConfig = ReadonlyArray<Field | Fields>;
36
+ interface Params {
37
+ body?: unknown;
38
+ headers: Record<string, unknown>;
39
+ path: Record<string, unknown>;
40
+ query: Record<string, unknown>;
41
+ }
42
+ export declare function buildClientParams(args: ReadonlyArray<unknown>, fields: FieldsConfig): Params;
43
+ export {};
@@ -0,0 +1,33 @@
1
+ interface SerializeOptions<T> extends SerializePrimitiveOptions, SerializerOptions<T> {
2
+ }
3
+ interface SerializePrimitiveOptions {
4
+ allowReserved?: boolean;
5
+ name: string;
6
+ }
7
+ export interface SerializerOptions<T> {
8
+ /**
9
+ * @default true
10
+ */
11
+ explode: boolean;
12
+ style: T;
13
+ }
14
+ export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited';
15
+ export type ArraySeparatorStyle = ArrayStyle | MatrixStyle;
16
+ type MatrixStyle = 'label' | 'matrix' | 'simple';
17
+ export type ObjectStyle = 'form' | 'deepObject';
18
+ type ObjectSeparatorStyle = ObjectStyle | MatrixStyle;
19
+ interface SerializePrimitiveParam extends SerializePrimitiveOptions {
20
+ value: string;
21
+ }
22
+ export declare const separatorArrayExplode: (style: ArraySeparatorStyle) => '.' | ';' | ',' | '&';
23
+ export declare const separatorArrayNoExplode: (style: ArraySeparatorStyle) => ',' | '|' | '%20';
24
+ export declare const separatorObjectExplode: (style: ObjectSeparatorStyle) => '.' | ';' | ',' | '&';
25
+ export declare const serializeArrayParam: ({ allowReserved, explode, name, style, value, }: SerializeOptions<ArraySeparatorStyle> & {
26
+ value: unknown[];
27
+ }) => string;
28
+ export declare const serializePrimitiveParam: ({ allowReserved, name, value, }: SerializePrimitiveParam) => string;
29
+ export declare const serializeObjectParam: ({ allowReserved, explode, name, style, value, valueOnly, }: SerializeOptions<ObjectSeparatorStyle> & {
30
+ value: Record<string, unknown> | Date;
31
+ valueOnly?: boolean;
32
+ }) => string;
33
+ export {};
@@ -0,0 +1,18 @@
1
+ /**
2
+ * JSON-friendly union that mirrors what Pinia Colada can hash.
3
+ */
4
+ export type JsonValue = null | string | number | boolean | JsonValue[] | {
5
+ [key: string]: JsonValue;
6
+ };
7
+ /**
8
+ * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes.
9
+ */
10
+ export declare const queryKeyJsonReplacer: (_key: string, value: unknown) => unknown | undefined;
11
+ /**
12
+ * Safely stringifies a value and parses it back into a JsonValue.
13
+ */
14
+ export declare const stringifyToJsonValue: (input: unknown) => JsonValue | undefined;
15
+ /**
16
+ * Normalizes any accepted value into a JSON-friendly shape for query keys.
17
+ */
18
+ export declare const serializeQueryKeyValue: (value: unknown) => JsonValue | undefined;
@@ -0,0 +1,71 @@
1
+ import type { Config } from './types.gen';
2
+ export type ServerSentEventsOptions<TData = unknown> = Omit<RequestInit, 'method'> & Pick<Config, 'method' | 'responseTransformer' | 'responseValidator'> & {
3
+ /**
4
+ * Fetch API implementation. You can use this option to provide a custom
5
+ * fetch instance.
6
+ *
7
+ * @default globalThis.fetch
8
+ */
9
+ fetch?: typeof fetch;
10
+ /**
11
+ * Implementing clients can call request interceptors inside this hook.
12
+ */
13
+ onRequest?: (url: string, init: RequestInit) => Promise<Request>;
14
+ /**
15
+ * Callback invoked when a network or parsing error occurs during streaming.
16
+ *
17
+ * This option applies only if the endpoint returns a stream of events.
18
+ *
19
+ * @param error The error that occurred.
20
+ */
21
+ onSseError?: (error: unknown) => void;
22
+ /**
23
+ * Callback invoked when an event is streamed from the server.
24
+ *
25
+ * This option applies only if the endpoint returns a stream of events.
26
+ *
27
+ * @param event Event streamed from the server.
28
+ * @returns Nothing (void).
29
+ */
30
+ onSseEvent?: (event: StreamEvent<TData>) => void;
31
+ serializedBody?: RequestInit['body'];
32
+ /**
33
+ * Default retry delay in milliseconds.
34
+ *
35
+ * This option applies only if the endpoint returns a stream of events.
36
+ *
37
+ * @default 3000
38
+ */
39
+ sseDefaultRetryDelay?: number;
40
+ /**
41
+ * Maximum number of retry attempts before giving up.
42
+ */
43
+ sseMaxRetryAttempts?: number;
44
+ /**
45
+ * Maximum retry delay in milliseconds.
46
+ *
47
+ * Applies only when exponential backoff is used.
48
+ *
49
+ * This option applies only if the endpoint returns a stream of events.
50
+ *
51
+ * @default 30000
52
+ */
53
+ sseMaxRetryDelay?: number;
54
+ /**
55
+ * Optional sleep function for retry backoff.
56
+ *
57
+ * Defaults to using `setTimeout`.
58
+ */
59
+ sseSleepFn?: (ms: number) => Promise<void>;
60
+ url: string;
61
+ };
62
+ export interface StreamEvent<TData = unknown> {
63
+ data: TData;
64
+ event?: string;
65
+ id?: string;
66
+ retry?: number;
67
+ }
68
+ export type ServerSentEventsResult<TData = unknown, TReturn = void, TNext = unknown> = {
69
+ stream: AsyncGenerator<TData extends Record<string, unknown> ? TData[keyof TData] : TData, TReturn, TNext>;
70
+ };
71
+ export declare function createSseClient<TData = unknown>({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }: ServerSentEventsOptions): ServerSentEventsResult<TData>;
@@ -0,0 +1,83 @@
1
+ import type { Auth, AuthToken } from './auth.gen';
2
+ import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen';
3
+ export type HttpMethod = 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace';
4
+ export type Client<RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never> = {
5
+ /**
6
+ * Returns the final request URL.
7
+ */
8
+ buildUrl: BuildUrlFn;
9
+ getConfig: () => Config;
10
+ request: RequestFn;
11
+ setConfig: (config: Config) => Config;
12
+ } & {
13
+ [K in HttpMethod]: MethodFn;
14
+ } & ([SseFn] extends [never] ? {
15
+ sse?: never;
16
+ } : {
17
+ sse: {
18
+ [K in HttpMethod]: SseFn;
19
+ };
20
+ });
21
+ export interface Config {
22
+ /**
23
+ * Auth token or a function returning auth token. The resolved value will be
24
+ * added to the request payload as defined by its `security` array.
25
+ */
26
+ auth?: ((auth: Auth) => Promise<AuthToken> | AuthToken) | AuthToken;
27
+ /**
28
+ * A function for serializing request body parameter. By default,
29
+ * {@link JSON.stringify()} will be used.
30
+ */
31
+ bodySerializer?: BodySerializer | null;
32
+ /**
33
+ * An object containing any HTTP headers that you want to pre-populate your
34
+ * `Headers` object with.
35
+ *
36
+ * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more}
37
+ */
38
+ headers?: RequestInit['headers'] | Record<string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown>;
39
+ /**
40
+ * The request method.
41
+ *
42
+ * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more}
43
+ */
44
+ method?: Uppercase<HttpMethod>;
45
+ /**
46
+ * A function for serializing request query parameters. By default, arrays
47
+ * will be exploded in form style, objects will be exploded in deepObject
48
+ * style, and reserved characters are percent-encoded.
49
+ *
50
+ * This method will have no effect if the native `paramsSerializer()` Axios
51
+ * API function is used.
52
+ *
53
+ * {@link https://swagger.io/docs/specification/serialization/#query View examples}
54
+ */
55
+ querySerializer?: QuerySerializer | QuerySerializerOptions;
56
+ /**
57
+ * A function validating request data. This is useful if you want to ensure
58
+ * the request conforms to the desired shape, so it can be safely sent to
59
+ * the server.
60
+ */
61
+ requestValidator?: (data: unknown) => Promise<unknown>;
62
+ /**
63
+ * A function transforming response data before it's returned. This is useful
64
+ * for post-processing data, e.g., converting ISO strings into Date objects.
65
+ */
66
+ responseTransformer?: (data: unknown) => Promise<unknown>;
67
+ /**
68
+ * A function validating response data. This is useful if you want to ensure
69
+ * the response conforms to the desired shape, so it can be safely passed to
70
+ * the transformers and returned to the user.
71
+ */
72
+ responseValidator?: (data: unknown) => Promise<unknown>;
73
+ }
74
+ /**
75
+ * Arbitrary metadata passed through the `meta` request option.
76
+ */
77
+ export interface ClientMeta {
78
+ }
79
+ type IsExactlyNeverOrNeverUndefined<T> = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false;
80
+ export type OmitNever<T extends Record<string, unknown>> = {
81
+ [K in keyof T as IsExactlyNeverOrNeverUndefined<T[K]> extends true ? never : K]: T[K];
82
+ };
83
+ export {};
@@ -0,0 +1,19 @@
1
+ import type { BodySerializer, QuerySerializer } from './bodySerializer.gen';
2
+ export interface PathSerializer {
3
+ path: Record<string, unknown>;
4
+ url: string;
5
+ }
6
+ export declare const PATH_PARAM_RE: RegExp;
7
+ export declare const defaultPathSerializer: ({ path, url: _url }: PathSerializer) => string;
8
+ export declare const getUrl: ({ baseUrl, path, query, querySerializer, url: _url, }: {
9
+ baseUrl?: string;
10
+ path?: Record<string, unknown>;
11
+ query?: Record<string, unknown>;
12
+ querySerializer: QuerySerializer;
13
+ url: string;
14
+ }) => string;
15
+ export declare function getValidRequestBody(options: {
16
+ body?: unknown;
17
+ bodySerializer?: BodySerializer | null;
18
+ serializedBody?: unknown;
19
+ }): unknown;