@fubar-it-co/tmdb-client 0.0.5

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.
@@ -0,0 +1,172 @@
1
+ // This file is auto-generated by @hey-api/openapi-ts
2
+ // @ts-nocheck
3
+
4
+ interface SerializeOptions<T> extends SerializePrimitiveOptions, SerializerOptions<T> {}
5
+
6
+ interface SerializePrimitiveOptions {
7
+ allowReserved?: boolean;
8
+ name: string;
9
+ }
10
+
11
+ export interface SerializerOptions<T> {
12
+ /**
13
+ * @default true
14
+ */
15
+ explode: boolean;
16
+ style: T;
17
+ }
18
+
19
+ export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited';
20
+ export type ArraySeparatorStyle = ArrayStyle | MatrixStyle;
21
+ type MatrixStyle = 'label' | 'matrix' | 'simple';
22
+ export type ObjectStyle = 'form' | 'deepObject';
23
+ type ObjectSeparatorStyle = ObjectStyle | MatrixStyle;
24
+
25
+ interface SerializePrimitiveParam extends SerializePrimitiveOptions {
26
+ value: string;
27
+ }
28
+
29
+ export const separatorArrayExplode = (style: ArraySeparatorStyle) => {
30
+ switch (style) {
31
+ case 'label':
32
+ return '.';
33
+ case 'matrix':
34
+ return ';';
35
+ case 'simple':
36
+ return ',';
37
+ default:
38
+ return '&';
39
+ }
40
+ };
41
+
42
+ export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => {
43
+ switch (style) {
44
+ case 'form':
45
+ return ',';
46
+ case 'pipeDelimited':
47
+ return '|';
48
+ case 'spaceDelimited':
49
+ return '%20';
50
+ default:
51
+ return ',';
52
+ }
53
+ };
54
+
55
+ export const separatorObjectExplode = (style: ObjectSeparatorStyle) => {
56
+ switch (style) {
57
+ case 'label':
58
+ return '.';
59
+ case 'matrix':
60
+ return ';';
61
+ case 'simple':
62
+ return ',';
63
+ default:
64
+ return '&';
65
+ }
66
+ };
67
+
68
+ export const serializeArrayParam = ({
69
+ allowReserved,
70
+ explode,
71
+ name,
72
+ style,
73
+ value,
74
+ }: SerializeOptions<ArraySeparatorStyle> & {
75
+ value: unknown[];
76
+ }) => {
77
+ if (!explode) {
78
+ const joinedValues = (
79
+ allowReserved ? value : value.map((v) => encodeURIComponent(v as string))
80
+ ).join(separatorArrayNoExplode(style));
81
+ switch (style) {
82
+ case 'label':
83
+ return `.${joinedValues}`;
84
+ case 'matrix':
85
+ return `;${name}=${joinedValues}`;
86
+ case 'simple':
87
+ return joinedValues;
88
+ default:
89
+ return `${name}=${joinedValues}`;
90
+ }
91
+ }
92
+
93
+ const separator = separatorArrayExplode(style);
94
+ const joinedValues = value
95
+ .map((v) => {
96
+ if (style === 'label' || style === 'simple') {
97
+ return allowReserved ? v : encodeURIComponent(v as string);
98
+ }
99
+
100
+ return serializePrimitiveParam({
101
+ allowReserved,
102
+ name,
103
+ value: v as string,
104
+ });
105
+ })
106
+ .join(separator);
107
+ return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues;
108
+ };
109
+
110
+ export const serializePrimitiveParam = ({
111
+ allowReserved,
112
+ name,
113
+ value,
114
+ }: SerializePrimitiveParam) => {
115
+ if (value === undefined || value === null) {
116
+ return '';
117
+ }
118
+
119
+ if (typeof value === 'object') {
120
+ throw new Error(
121
+ 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.',
122
+ );
123
+ }
124
+
125
+ return `${name}=${allowReserved ? value : encodeURIComponent(value)}`;
126
+ };
127
+
128
+ export const serializeObjectParam = ({
129
+ allowReserved,
130
+ explode,
131
+ name,
132
+ style,
133
+ value,
134
+ valueOnly,
135
+ }: SerializeOptions<ObjectSeparatorStyle> & {
136
+ value: Record<string, unknown> | Date;
137
+ valueOnly?: boolean;
138
+ }) => {
139
+ if (value instanceof Date) {
140
+ return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`;
141
+ }
142
+
143
+ if (style !== 'deepObject' && !explode) {
144
+ let values: string[] = [];
145
+ Object.entries(value).forEach(([key, v]) => {
146
+ values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)];
147
+ });
148
+ const joinedValues = values.join(',');
149
+ switch (style) {
150
+ case 'form':
151
+ return `${name}=${joinedValues}`;
152
+ case 'label':
153
+ return `.${joinedValues}`;
154
+ case 'matrix':
155
+ return `;${name}=${joinedValues}`;
156
+ default:
157
+ return joinedValues;
158
+ }
159
+ }
160
+
161
+ const separator = separatorObjectExplode(style);
162
+ const joinedValues = Object.entries(value)
163
+ .map(([key, v]) =>
164
+ serializePrimitiveParam({
165
+ allowReserved,
166
+ name: style === 'deepObject' ? `${name}[${key}]` : key,
167
+ value: v as string,
168
+ }),
169
+ )
170
+ .join(separator);
171
+ return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues;
172
+ };
@@ -0,0 +1,118 @@
1
+ // This file is auto-generated by @hey-api/openapi-ts
2
+ // @ts-nocheck
3
+
4
+ /**
5
+ * JSON-friendly union that mirrors what Pinia Colada can hash.
6
+ */
7
+ export type JsonValue =
8
+ | null
9
+ | string
10
+ | number
11
+ | boolean
12
+ | JsonValue[]
13
+ | { [key: string]: JsonValue };
14
+
15
+ /**
16
+ * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes.
17
+ */
18
+ export const queryKeyJsonReplacer = (_key: string, value: unknown) => {
19
+ if (value === undefined || typeof value === 'function' || typeof value === 'symbol') {
20
+ return undefined;
21
+ }
22
+ if (typeof value === 'bigint') {
23
+ return value.toString();
24
+ }
25
+ if (value instanceof Date) {
26
+ return value.toISOString();
27
+ }
28
+ return value;
29
+ };
30
+
31
+ /**
32
+ * Safely stringifies a value and parses it back into a JsonValue.
33
+ */
34
+ export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => {
35
+ try {
36
+ const json = JSON.stringify(input, queryKeyJsonReplacer);
37
+ if (json === undefined) {
38
+ return undefined;
39
+ }
40
+ return JSON.parse(json) as JsonValue;
41
+ } catch {
42
+ return undefined;
43
+ }
44
+ };
45
+
46
+ /**
47
+ * Detects plain objects (including objects with a null prototype).
48
+ */
49
+ const isPlainObject = (value: unknown): value is Record<string, unknown> => {
50
+ if (value === null || typeof value !== 'object') {
51
+ return false;
52
+ }
53
+ const prototype = Object.getPrototypeOf(value as object);
54
+ return prototype === Object.prototype || prototype === null;
55
+ };
56
+
57
+ /**
58
+ * Turns URLSearchParams into a sorted JSON object for deterministic keys.
59
+ */
60
+ const serializeSearchParams = (params: URLSearchParams): JsonValue => {
61
+ const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b));
62
+ const result: Record<string, JsonValue> = {};
63
+
64
+ for (const [key, value] of entries) {
65
+ const existing = result[key];
66
+ if (existing === undefined) {
67
+ result[key] = value;
68
+ continue;
69
+ }
70
+
71
+ if (Array.isArray(existing)) {
72
+ (existing as string[]).push(value);
73
+ } else {
74
+ result[key] = [existing, value];
75
+ }
76
+ }
77
+
78
+ return result;
79
+ };
80
+
81
+ /**
82
+ * Normalizes any accepted value into a JSON-friendly shape for query keys.
83
+ */
84
+ export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => {
85
+ if (value === null) {
86
+ return null;
87
+ }
88
+
89
+ if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {
90
+ return value;
91
+ }
92
+
93
+ if (value === undefined || typeof value === 'function' || typeof value === 'symbol') {
94
+ return undefined;
95
+ }
96
+
97
+ if (typeof value === 'bigint') {
98
+ return value.toString();
99
+ }
100
+
101
+ if (value instanceof Date) {
102
+ return value.toISOString();
103
+ }
104
+
105
+ if (Array.isArray(value)) {
106
+ return stringifyToJsonValue(value);
107
+ }
108
+
109
+ if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) {
110
+ return serializeSearchParams(value);
111
+ }
112
+
113
+ if (isPlainObject(value)) {
114
+ return stringifyToJsonValue(value);
115
+ }
116
+
117
+ return undefined;
118
+ };
@@ -0,0 +1,244 @@
1
+ // This file is auto-generated by @hey-api/openapi-ts
2
+ // @ts-nocheck
3
+
4
+ import type { Config } from './types.gen';
5
+
6
+ export type ServerSentEventsOptions<TData = unknown> = Omit<RequestInit, 'method'> &
7
+ Pick<Config, 'method' | 'responseTransformer' | 'responseValidator'> & {
8
+ /**
9
+ * Fetch API implementation. You can use this option to provide a custom
10
+ * fetch instance.
11
+ *
12
+ * @default globalThis.fetch
13
+ */
14
+ fetch?: typeof fetch;
15
+ /**
16
+ * Implementing clients can call request interceptors inside this hook.
17
+ */
18
+ onRequest?: (url: string, init: RequestInit) => Promise<Request>;
19
+ /**
20
+ * Callback invoked when a network or parsing error occurs during streaming.
21
+ *
22
+ * This option applies only if the endpoint returns a stream of events.
23
+ *
24
+ * @param error The error that occurred.
25
+ */
26
+ onSseError?: (error: unknown) => void;
27
+ /**
28
+ * Callback invoked when an event is streamed from the server.
29
+ *
30
+ * This option applies only if the endpoint returns a stream of events.
31
+ *
32
+ * @param event Event streamed from the server.
33
+ * @returns Nothing (void).
34
+ */
35
+ onSseEvent?: (event: StreamEvent<TData>) => void;
36
+ serializedBody?: RequestInit['body'];
37
+ /**
38
+ * Default retry delay in milliseconds.
39
+ *
40
+ * This option applies only if the endpoint returns a stream of events.
41
+ *
42
+ * @default 3000
43
+ */
44
+ sseDefaultRetryDelay?: number;
45
+ /**
46
+ * Maximum number of retry attempts before giving up.
47
+ */
48
+ sseMaxRetryAttempts?: number;
49
+ /**
50
+ * Maximum retry delay in milliseconds.
51
+ *
52
+ * Applies only when exponential backoff is used.
53
+ *
54
+ * This option applies only if the endpoint returns a stream of events.
55
+ *
56
+ * @default 30000
57
+ */
58
+ sseMaxRetryDelay?: number;
59
+ /**
60
+ * Optional sleep function for retry backoff.
61
+ *
62
+ * Defaults to using `setTimeout`.
63
+ */
64
+ sseSleepFn?: (ms: number) => Promise<void>;
65
+ url: string;
66
+ };
67
+
68
+ export interface StreamEvent<TData = unknown> {
69
+ data: TData;
70
+ event?: string;
71
+ id?: string;
72
+ retry?: number;
73
+ }
74
+
75
+ export type ServerSentEventsResult<TData = unknown, TReturn = void, TNext = unknown> = {
76
+ stream: AsyncGenerator<
77
+ TData extends Record<string, unknown> ? TData[keyof TData] : TData,
78
+ TReturn,
79
+ TNext
80
+ >;
81
+ };
82
+
83
+ export const createSseClient = <TData = unknown>({
84
+ onRequest,
85
+ onSseError,
86
+ onSseEvent,
87
+ responseTransformer,
88
+ responseValidator,
89
+ sseDefaultRetryDelay,
90
+ sseMaxRetryAttempts,
91
+ sseMaxRetryDelay,
92
+ sseSleepFn,
93
+ url,
94
+ ...options
95
+ }: ServerSentEventsOptions): ServerSentEventsResult<TData> => {
96
+ let lastEventId: string | undefined;
97
+
98
+ const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms)));
99
+
100
+ const createStream = async function* () {
101
+ let retryDelay: number = sseDefaultRetryDelay ?? 3000;
102
+ let attempt = 0;
103
+ const signal = options.signal ?? new AbortController().signal;
104
+
105
+ while (true) {
106
+ if (signal.aborted) break;
107
+
108
+ attempt++;
109
+
110
+ const headers =
111
+ options.headers instanceof Headers
112
+ ? options.headers
113
+ : new Headers(options.headers as Record<string, string> | undefined);
114
+
115
+ if (lastEventId !== undefined) {
116
+ headers.set('Last-Event-ID', lastEventId);
117
+ }
118
+
119
+ try {
120
+ const requestInit: RequestInit = {
121
+ redirect: 'follow',
122
+ ...options,
123
+ body: options.serializedBody,
124
+ headers,
125
+ signal,
126
+ };
127
+ let request = new Request(url, requestInit);
128
+ if (onRequest) {
129
+ request = await onRequest(url, requestInit);
130
+ }
131
+ // fetch must be assigned here, otherwise it would throw the error:
132
+ // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation
133
+ const _fetch = options.fetch ?? globalThis.fetch;
134
+ const response = await _fetch(request);
135
+
136
+ if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`);
137
+
138
+ if (!response.body) throw new Error('No body in SSE response');
139
+
140
+ const reader = response.body.pipeThrough(new TextDecoderStream()).getReader();
141
+
142
+ let buffer = '';
143
+
144
+ const abortHandler = () => {
145
+ try {
146
+ reader.cancel();
147
+ } catch {
148
+ // noop
149
+ }
150
+ };
151
+
152
+ signal.addEventListener('abort', abortHandler);
153
+
154
+ try {
155
+ while (true) {
156
+ const { done, value } = await reader.read();
157
+ if (done) break;
158
+ buffer += value;
159
+ // Normalize line endings: CRLF -> LF, then CR -> LF
160
+ buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n');
161
+
162
+ const chunks = buffer.split('\n\n');
163
+ buffer = chunks.pop() ?? '';
164
+
165
+ for (const chunk of chunks) {
166
+ const lines = chunk.split('\n');
167
+ const dataLines: Array<string> = [];
168
+ let eventName: string | undefined;
169
+
170
+ for (const line of lines) {
171
+ if (line.startsWith('data:')) {
172
+ dataLines.push(line.replace(/^data:\s*/, ''));
173
+ } else if (line.startsWith('event:')) {
174
+ eventName = line.replace(/^event:\s*/, '');
175
+ } else if (line.startsWith('id:')) {
176
+ lastEventId = line.replace(/^id:\s*/, '');
177
+ } else if (line.startsWith('retry:')) {
178
+ const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10);
179
+ if (!Number.isNaN(parsed)) {
180
+ retryDelay = parsed;
181
+ }
182
+ }
183
+ }
184
+
185
+ let data: unknown;
186
+ let parsedJson = false;
187
+
188
+ if (dataLines.length) {
189
+ const rawData = dataLines.join('\n');
190
+ try {
191
+ data = JSON.parse(rawData);
192
+ parsedJson = true;
193
+ } catch {
194
+ data = rawData;
195
+ }
196
+ }
197
+
198
+ if (parsedJson) {
199
+ if (responseValidator) {
200
+ await responseValidator(data);
201
+ }
202
+
203
+ if (responseTransformer) {
204
+ data = await responseTransformer(data);
205
+ }
206
+ }
207
+
208
+ onSseEvent?.({
209
+ data,
210
+ event: eventName,
211
+ id: lastEventId,
212
+ retry: retryDelay,
213
+ });
214
+
215
+ if (dataLines.length) {
216
+ yield data as any;
217
+ }
218
+ }
219
+ }
220
+ } finally {
221
+ signal.removeEventListener('abort', abortHandler);
222
+ reader.releaseLock();
223
+ }
224
+
225
+ break; // exit loop on normal completion
226
+ } catch (error) {
227
+ // connection failed or aborted; retry after delay
228
+ onSseError?.(error);
229
+
230
+ if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) {
231
+ break; // stop after firing error
232
+ }
233
+
234
+ // exponential backoff: double retry each attempt, cap at 30s
235
+ const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000);
236
+ await sleep(backoff);
237
+ }
238
+ }
239
+ };
240
+
241
+ const stream = createStream();
242
+
243
+ return { stream };
244
+ };
@@ -0,0 +1,105 @@
1
+ // This file is auto-generated by @hey-api/openapi-ts
2
+ // @ts-nocheck
3
+
4
+ import type { Auth, AuthToken } from './auth.gen';
5
+ import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen';
6
+
7
+ export type HttpMethod =
8
+ | 'connect'
9
+ | 'delete'
10
+ | 'get'
11
+ | 'head'
12
+ | 'options'
13
+ | 'patch'
14
+ | 'post'
15
+ | 'put'
16
+ | 'trace';
17
+
18
+ export type Client<
19
+ RequestFn = never,
20
+ Config = unknown,
21
+ MethodFn = never,
22
+ BuildUrlFn = never,
23
+ SseFn = never,
24
+ > = {
25
+ /**
26
+ * Returns the final request URL.
27
+ */
28
+ buildUrl: BuildUrlFn;
29
+ getConfig: () => Config;
30
+ request: RequestFn;
31
+ setConfig: (config: Config) => Config;
32
+ } & {
33
+ [K in HttpMethod]: MethodFn;
34
+ } & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } });
35
+
36
+ export interface Config {
37
+ /**
38
+ * Auth token or a function returning auth token. The resolved value will be
39
+ * added to the request payload as defined by its `security` array.
40
+ */
41
+ auth?: ((auth: Auth) => Promise<AuthToken> | AuthToken) | AuthToken;
42
+ /**
43
+ * A function for serializing request body parameter. By default,
44
+ * {@link JSON.stringify()} will be used.
45
+ */
46
+ bodySerializer?: BodySerializer | null;
47
+ /**
48
+ * An object containing any HTTP headers that you want to pre-populate your
49
+ * `Headers` object with.
50
+ *
51
+ * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more}
52
+ */
53
+ headers?:
54
+ | RequestInit['headers']
55
+ | Record<
56
+ string,
57
+ string | number | boolean | (string | number | boolean)[] | null | undefined | unknown
58
+ >;
59
+ /**
60
+ * The request method.
61
+ *
62
+ * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more}
63
+ */
64
+ method?: Uppercase<HttpMethod>;
65
+ /**
66
+ * A function for serializing request query parameters. By default, arrays
67
+ * will be exploded in form style, objects will be exploded in deepObject
68
+ * style, and reserved characters are percent-encoded.
69
+ *
70
+ * This method will have no effect if the native `paramsSerializer()` Axios
71
+ * API function is used.
72
+ *
73
+ * {@link https://swagger.io/docs/specification/serialization/#query View examples}
74
+ */
75
+ querySerializer?: QuerySerializer | QuerySerializerOptions;
76
+ /**
77
+ * A function validating request data. This is useful if you want to ensure
78
+ * the request conforms to the desired shape, so it can be safely sent to
79
+ * the server.
80
+ */
81
+ requestValidator?: (data: unknown) => Promise<unknown>;
82
+ /**
83
+ * A function transforming response data before it's returned. This is useful
84
+ * for post-processing data, e.g. converting ISO strings into Date objects.
85
+ */
86
+ responseTransformer?: (data: unknown) => Promise<unknown>;
87
+ /**
88
+ * A function validating response data. This is useful if you want to ensure
89
+ * the response conforms to the desired shape, so it can be safely passed to
90
+ * the transformers and returned to the user.
91
+ */
92
+ responseValidator?: (data: unknown) => Promise<unknown>;
93
+ }
94
+
95
+ type IsExactlyNeverOrNeverUndefined<T> = [T] extends [never]
96
+ ? true
97
+ : [T] extends [never | undefined]
98
+ ? [undefined] extends [T]
99
+ ? false
100
+ : true
101
+ : false;
102
+
103
+ export type OmitNever<T extends Record<string, unknown>> = {
104
+ [K in keyof T as IsExactlyNeverOrNeverUndefined<T[K]> extends true ? never : K]: T[K];
105
+ };