atelino-sdk 1.0.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.
@@ -0,0 +1,132 @@
1
+ // This file is auto-generated by @hey-api/openapi-ts
2
+ export function createSseClient({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }) {
3
+ let lastEventId;
4
+ const sleep = sseSleepFn ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
5
+ const createStream = async function* () {
6
+ let retryDelay = sseDefaultRetryDelay ?? 3000;
7
+ let attempt = 0;
8
+ const signal = options.signal ?? new AbortController().signal;
9
+ while (true) {
10
+ if (signal.aborted)
11
+ break;
12
+ attempt++;
13
+ const headers = options.headers instanceof Headers
14
+ ? options.headers
15
+ : new Headers(options.headers);
16
+ if (lastEventId !== undefined) {
17
+ headers.set('Last-Event-ID', lastEventId);
18
+ }
19
+ try {
20
+ const requestInit = {
21
+ redirect: 'follow',
22
+ ...options,
23
+ body: options.serializedBody,
24
+ headers,
25
+ signal,
26
+ };
27
+ let request = new Request(url, requestInit);
28
+ if (onRequest) {
29
+ request = await onRequest(url, requestInit);
30
+ }
31
+ // fetch must be assigned here, otherwise it would throw the error:
32
+ // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation
33
+ const _fetch = options.fetch ?? globalThis.fetch;
34
+ const response = await _fetch(request);
35
+ if (!response.ok)
36
+ throw new Error(`SSE failed: ${response.status} ${response.statusText}`);
37
+ if (!response.body)
38
+ throw new Error('No body in SSE response');
39
+ const reader = response.body.pipeThrough(new TextDecoderStream()).getReader();
40
+ let buffer = '';
41
+ const abortHandler = () => {
42
+ try {
43
+ reader.cancel();
44
+ }
45
+ catch {
46
+ // noop
47
+ }
48
+ };
49
+ signal.addEventListener('abort', abortHandler);
50
+ try {
51
+ while (true) {
52
+ const { done, value } = await reader.read();
53
+ if (done)
54
+ break;
55
+ buffer += value;
56
+ buffer = buffer.replace(/\r\n?/g, '\n'); // normalize line endings
57
+ const chunks = buffer.split('\n\n');
58
+ buffer = chunks.pop() ?? '';
59
+ for (const chunk of chunks) {
60
+ const lines = chunk.split('\n');
61
+ const dataLines = [];
62
+ let eventName;
63
+ for (const line of lines) {
64
+ if (line.startsWith('data:')) {
65
+ dataLines.push(line.replace(/^data:\s*/, ''));
66
+ }
67
+ else if (line.startsWith('event:')) {
68
+ eventName = line.replace(/^event:\s*/, '');
69
+ }
70
+ else if (line.startsWith('id:')) {
71
+ lastEventId = line.replace(/^id:\s*/, '');
72
+ }
73
+ else if (line.startsWith('retry:')) {
74
+ const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10);
75
+ if (!Number.isNaN(parsed)) {
76
+ retryDelay = parsed;
77
+ }
78
+ }
79
+ }
80
+ let data;
81
+ let parsedJson = false;
82
+ if (dataLines.length) {
83
+ const rawData = dataLines.join('\n');
84
+ try {
85
+ data = JSON.parse(rawData);
86
+ parsedJson = true;
87
+ }
88
+ catch {
89
+ data = rawData;
90
+ }
91
+ }
92
+ if (parsedJson) {
93
+ if (responseValidator) {
94
+ await responseValidator(data);
95
+ }
96
+ if (responseTransformer) {
97
+ data = await responseTransformer(data);
98
+ }
99
+ }
100
+ onSseEvent?.({
101
+ data,
102
+ event: eventName,
103
+ id: lastEventId,
104
+ retry: retryDelay,
105
+ });
106
+ if (dataLines.length) {
107
+ yield data;
108
+ }
109
+ }
110
+ }
111
+ }
112
+ finally {
113
+ signal.removeEventListener('abort', abortHandler);
114
+ reader.releaseLock();
115
+ }
116
+ break; // exit loop on normal completion
117
+ }
118
+ catch (error) {
119
+ // connection failed or aborted; retry after delay
120
+ onSseError?.(error);
121
+ if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) {
122
+ break; // stop after firing error
123
+ }
124
+ // exponential backoff: double retry each attempt, cap at 30s
125
+ const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000);
126
+ await sleep(backoff);
127
+ }
128
+ }
129
+ };
130
+ const stream = createStream();
131
+ return { stream };
132
+ }
@@ -0,0 +1,78 @@
1
+ import type { Auth, AuthToken } from './auth.gen.js';
2
+ import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen.js';
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
+ type IsExactlyNeverOrNeverUndefined<T> = [T] extends [never] ? true : [T] extends [never | undefined] ? [undefined] extends [T] ? false : true : false;
75
+ export type OmitNever<T extends Record<string, unknown>> = {
76
+ [K in keyof T as IsExactlyNeverOrNeverUndefined<T[K]> extends true ? never : K]: T[K];
77
+ };
78
+ export {};
@@ -0,0 +1,2 @@
1
+ // This file is auto-generated by @hey-api/openapi-ts
2
+ export {};
@@ -0,0 +1,19 @@
1
+ import type { BodySerializer, QuerySerializer } from './bodySerializer.gen.js';
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;
@@ -0,0 +1,87 @@
1
+ // This file is auto-generated by @hey-api/openapi-ts
2
+ import { serializeArrayParam, serializeObjectParam, serializePrimitiveParam, } from './pathSerializer.gen.js';
3
+ export const PATH_PARAM_RE = /\{[^{}]+\}/g;
4
+ export const defaultPathSerializer = ({ path, url: _url }) => {
5
+ let url = _url;
6
+ const matches = _url.match(PATH_PARAM_RE);
7
+ if (matches) {
8
+ for (const match of matches) {
9
+ let explode = false;
10
+ let name = match.substring(1, match.length - 1);
11
+ let style = 'simple';
12
+ if (name.endsWith('*')) {
13
+ explode = true;
14
+ name = name.substring(0, name.length - 1);
15
+ }
16
+ if (name.startsWith('.')) {
17
+ name = name.substring(1);
18
+ style = 'label';
19
+ }
20
+ else if (name.startsWith(';')) {
21
+ name = name.substring(1);
22
+ style = 'matrix';
23
+ }
24
+ const value = path[name];
25
+ if (value === undefined || value === null) {
26
+ continue;
27
+ }
28
+ if (Array.isArray(value)) {
29
+ url = url.replace(match, serializeArrayParam({ explode, name, style, value }));
30
+ continue;
31
+ }
32
+ if (typeof value === 'object') {
33
+ url = url.replace(match, serializeObjectParam({
34
+ explode,
35
+ name,
36
+ style,
37
+ value: value,
38
+ valueOnly: true,
39
+ }));
40
+ continue;
41
+ }
42
+ if (style === 'matrix') {
43
+ url = url.replace(match, `;${serializePrimitiveParam({
44
+ name,
45
+ value: value,
46
+ })}`);
47
+ continue;
48
+ }
49
+ const replaceValue = encodeURIComponent(style === 'label' ? `.${value}` : value);
50
+ url = url.replace(match, replaceValue);
51
+ }
52
+ }
53
+ return url;
54
+ };
55
+ export const getUrl = ({ baseUrl, path, query, querySerializer, url: _url, }) => {
56
+ const pathUrl = _url.startsWith('/') ? _url : `/${_url}`;
57
+ let url = (baseUrl ?? '') + pathUrl;
58
+ if (path) {
59
+ url = defaultPathSerializer({ path, url });
60
+ }
61
+ let search = query ? querySerializer(query) : '';
62
+ if (search.startsWith('?')) {
63
+ search = search.substring(1);
64
+ }
65
+ if (search) {
66
+ url += `?${search}`;
67
+ }
68
+ return url;
69
+ };
70
+ export function getValidRequestBody(options) {
71
+ const hasBody = options.body !== undefined;
72
+ const isSerializedBody = hasBody && options.bodySerializer;
73
+ if (isSerializedBody) {
74
+ if ('serializedBody' in options) {
75
+ const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== '';
76
+ return hasSerializedBody ? options.serializedBody : null;
77
+ }
78
+ // not all clients implement a serializedBody property (i.e., client-axios)
79
+ return options.body !== '' ? options.body : null;
80
+ }
81
+ // plain/text body
82
+ if (hasBody) {
83
+ return options.body;
84
+ }
85
+ // no body was provided
86
+ return undefined;
87
+ }
@@ -0,0 +1,2 @@
1
+ export { deleteHitokotoById, type Options, postHitokoto } from './sdk.gen.js';
2
+ export type { AtelinoInternalDtoCreateHitokotoRequest, AtelinoInternalDtoHitokotoIdRequest, AtelinoInternalDtoResponse, ClientOptions, DeleteHitokotoByIdData, DeleteHitokotoByIdError, DeleteHitokotoByIdErrors, DeleteHitokotoByIdResponse, DeleteHitokotoByIdResponses, PostHitokotoData, PostHitokotoError, PostHitokotoErrors, PostHitokotoResponse, PostHitokotoResponses } from './types.gen.js';
package/dist/index.js ADDED
@@ -0,0 +1,2 @@
1
+ // This file is auto-generated by @hey-api/openapi-ts
2
+ export { deleteHitokotoById, postHitokoto } from './sdk.gen.js';
@@ -0,0 +1,27 @@
1
+ import type { Client, Options as Options2, TDataShape } from './client/index.js';
2
+ import type { DeleteHitokotoByIdData, DeleteHitokotoByIdErrors, DeleteHitokotoByIdResponses, PostHitokotoData, PostHitokotoErrors, PostHitokotoResponses } from './types.gen.js';
3
+ export type Options<TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown> = Options2<TData, ThrowOnError, TResponse> & {
4
+ /**
5
+ * You can provide a client instance returned by `createClient()` instead of
6
+ * individual options. This might be also useful if you want to implement a
7
+ * custom client.
8
+ */
9
+ client?: Client;
10
+ /**
11
+ * You can pass arbitrary values through the `meta` object. This can be
12
+ * used to access values that aren't defined as part of the SDK function.
13
+ */
14
+ meta?: Record<string, unknown>;
15
+ };
16
+ /**
17
+ * 添加一言
18
+ *
19
+ * 创建一条新的一言记录。如果内容已存在,则返回 409 冲突错误;其他数据库异常返回 500。
20
+ */
21
+ export declare const postHitokoto: <ThrowOnError extends boolean = false>(options: Options<PostHitokotoData, ThrowOnError>) => import("./client/types.gen.js").RequestResult<PostHitokotoResponses, PostHitokotoErrors, ThrowOnError, "fields">;
22
+ /**
23
+ * 删除一言
24
+ *
25
+ * 传入一言的 ID,从数据库中删除对应的记录。若 ID 不存在则返回 404,数据库异常则返回 500。
26
+ */
27
+ export declare const deleteHitokotoById: <ThrowOnError extends boolean = false>(options: Options<DeleteHitokotoByIdData, ThrowOnError>) => import("./client/types.gen.js").RequestResult<DeleteHitokotoByIdResponses, DeleteHitokotoByIdErrors, ThrowOnError, "fields">;
@@ -0,0 +1,26 @@
1
+ // This file is auto-generated by @hey-api/openapi-ts
2
+ import { client } from './client.gen.js';
3
+ /**
4
+ * 添加一言
5
+ *
6
+ * 创建一条新的一言记录。如果内容已存在,则返回 409 冲突错误;其他数据库异常返回 500。
7
+ */
8
+ export const postHitokoto = (options) => (options.client ?? client).post({
9
+ security: [{ scheme: 'basic', type: 'http' }],
10
+ url: '/hitokoto',
11
+ ...options,
12
+ headers: {
13
+ 'Content-Type': 'application/json',
14
+ ...options.headers
15
+ }
16
+ });
17
+ /**
18
+ * 删除一言
19
+ *
20
+ * 传入一言的 ID,从数据库中删除对应的记录。若 ID 不存在则返回 404,数据库异常则返回 500。
21
+ */
22
+ export const deleteHitokotoById = (options) => (options.client ?? client).delete({
23
+ security: [{ scheme: 'basic', type: 'http' }],
24
+ url: '/hitokoto/{id}',
25
+ ...options
26
+ });
@@ -0,0 +1,110 @@
1
+ export type ClientOptions = {
2
+ baseUrl: 'https://localhost:8080/api/' | (string & {});
3
+ };
4
+ export type AtelinoInternalDtoCreateHitokotoRequest = {
5
+ content: string;
6
+ };
7
+ export type AtelinoInternalDtoHitokotoIdRequest = {
8
+ id: number;
9
+ };
10
+ export type AtelinoInternalDtoResponse = {
11
+ code?: number;
12
+ data?: unknown;
13
+ message?: string;
14
+ };
15
+ export type PostHitokotoData = {
16
+ /**
17
+ * 一言内容
18
+ */
19
+ body: AtelinoInternalDtoCreateHitokotoRequest;
20
+ path?: never;
21
+ query?: never;
22
+ url: '/hitokoto';
23
+ };
24
+ export type PostHitokotoErrors = {
25
+ /**
26
+ * 请求参数错误
27
+ */
28
+ 400: AtelinoInternalDtoResponse & {
29
+ code?: number;
30
+ message?: string;
31
+ };
32
+ /**
33
+ * 该一言已存在
34
+ */
35
+ 409: AtelinoInternalDtoResponse & {
36
+ code?: number;
37
+ message?: string;
38
+ };
39
+ /**
40
+ * 数据库错误
41
+ */
42
+ 500: AtelinoInternalDtoResponse & {
43
+ code?: number;
44
+ message?: string;
45
+ };
46
+ };
47
+ export type PostHitokotoError = PostHitokotoErrors[keyof PostHitokotoErrors];
48
+ export type PostHitokotoResponses = {
49
+ /**
50
+ * 添加成功
51
+ */
52
+ 200: AtelinoInternalDtoResponse & {
53
+ code?: number;
54
+ data?: AtelinoInternalDtoHitokotoIdRequest;
55
+ message?: string;
56
+ };
57
+ };
58
+ export type PostHitokotoResponse = PostHitokotoResponses[keyof PostHitokotoResponses];
59
+ export type DeleteHitokotoByIdData = {
60
+ body?: never;
61
+ path: {
62
+ /**
63
+ * 一言 ID
64
+ */
65
+ id: number;
66
+ };
67
+ query?: never;
68
+ url: '/hitokoto/{id}';
69
+ };
70
+ export type DeleteHitokotoByIdErrors = {
71
+ /**
72
+ * 请求参数错误
73
+ */
74
+ 400: AtelinoInternalDtoResponse & {
75
+ code?: number;
76
+ message?: string;
77
+ };
78
+ /**
79
+ * 未授权
80
+ */
81
+ 401: AtelinoInternalDtoResponse & {
82
+ code?: number;
83
+ message?: string;
84
+ };
85
+ /**
86
+ * 没有找到对应的一言
87
+ */
88
+ 404: AtelinoInternalDtoResponse & {
89
+ code?: number;
90
+ message?: string;
91
+ };
92
+ /**
93
+ * 数据库错误
94
+ */
95
+ 500: AtelinoInternalDtoResponse & {
96
+ code?: number;
97
+ message?: string;
98
+ };
99
+ };
100
+ export type DeleteHitokotoByIdError = DeleteHitokotoByIdErrors[keyof DeleteHitokotoByIdErrors];
101
+ export type DeleteHitokotoByIdResponses = {
102
+ /**
103
+ * 删除成功
104
+ */
105
+ 200: AtelinoInternalDtoResponse & {
106
+ code?: number;
107
+ message?: string;
108
+ };
109
+ };
110
+ export type DeleteHitokotoByIdResponse = DeleteHitokotoByIdResponses[keyof DeleteHitokotoByIdResponses];
@@ -0,0 +1,2 @@
1
+ // This file is auto-generated by @hey-api/openapi-ts
2
+ export {};
package/package.json ADDED
@@ -0,0 +1,37 @@
1
+ {
2
+ "name": "atelino-sdk",
3
+ "version": "1.0.1",
4
+ "author": "BAIYI",
5
+ "type": "module",
6
+ "main": "./dist/index.js",
7
+ "types": "./dist/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "import": "./dist/index.js",
11
+ "types": "./dist/index.d.ts"
12
+ }
13
+ },
14
+ "files": [
15
+ "dist/"
16
+ ],
17
+ "scripts": {
18
+ "build": "tsc",
19
+ "dev": "tsc --watch",
20
+ "prepublishOnly": "npm run build",
21
+ "generate": "openapi-ts"
22
+ },
23
+ "devDependencies": {
24
+ "@hey-api/client-fetch": "^0.13.1",
25
+ "@hey-api/openapi-ts": "^0.97.1",
26
+ "@types/node": "^25.6.2",
27
+ "typescript": "^6.0.3"
28
+ },
29
+ "publishConfig": {
30
+ "registry": "https://registry.npmjs.org/"
31
+ },
32
+ "license": "MIT",
33
+ "repository": {
34
+ "type": "git",
35
+ "url": "https://github.com/baiyibs/atelino-sdk.git"
36
+ }
37
+ }