@kevisual/api 0.0.42 → 0.0.44

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,336 @@
1
+ // node_modules/.pnpm/@kevisual+query@0.0.39/node_modules/@kevisual/query/dist/query-browser.js
2
+ var isTextForContentType = (contentType) => {
3
+ if (!contentType)
4
+ return false;
5
+ const textTypes = ["text/", "xml", "html", "javascript", "css", "csv", "plain", "x-www-form-urlencoded", "md"];
6
+ return textTypes.some((type) => contentType.includes(type));
7
+ };
8
+ var adapter = async (opts = {}, overloadOpts) => {
9
+ const controller = new AbortController;
10
+ const signal = controller.signal;
11
+ const isPostFile = opts.isPostFile || false;
12
+ let responseType = opts.responseType || "json";
13
+ if (opts.isBlob) {
14
+ responseType = "blob";
15
+ } else if (opts.isText) {
16
+ responseType = "text";
17
+ }
18
+ const timeout = opts.timeout || 60000 * 3;
19
+ const timer = setTimeout(() => {
20
+ controller.abort();
21
+ }, timeout);
22
+ let method = overloadOpts?.method || opts?.method || "POST";
23
+ let headers = { ...opts?.headers, ...overloadOpts?.headers };
24
+ let origin = "";
25
+ let url;
26
+ if (opts?.url?.startsWith("http")) {
27
+ url = new URL(opts.url);
28
+ } else {
29
+ origin = window?.location?.origin || "http://localhost:51515";
30
+ url = new URL(opts.url, origin);
31
+ }
32
+ const isGet = method === "GET";
33
+ const oldSearchParams = url.searchParams;
34
+ if (isGet) {
35
+ let searchParams = new URLSearchParams({ ...Object.fromEntries(oldSearchParams), ...opts.body });
36
+ url.search = searchParams.toString();
37
+ } else {
38
+ const params = {
39
+ ...Object.fromEntries(oldSearchParams),
40
+ ...opts.params
41
+ };
42
+ const searchParams = new URLSearchParams(params);
43
+ if (typeof opts.body === "object" && opts.body !== null) {
44
+ let body2 = opts.body || {};
45
+ if (!params.path && body2?.path) {
46
+ searchParams.set("path", body2.path);
47
+ if (body2?.key) {
48
+ searchParams.set("key", body2.key);
49
+ }
50
+ }
51
+ }
52
+ url.search = searchParams.toString();
53
+ }
54
+ let body = undefined;
55
+ if (isGet) {
56
+ body = undefined;
57
+ } else if (isPostFile) {
58
+ body = opts.body;
59
+ } else {
60
+ headers = {
61
+ "Content-Type": "application/json",
62
+ ...headers
63
+ };
64
+ body = JSON.stringify(opts.body);
65
+ }
66
+ return fetch(url, {
67
+ method: method.toUpperCase(),
68
+ signal,
69
+ body,
70
+ ...overloadOpts,
71
+ headers
72
+ }).then(async (response) => {
73
+ const contentType = response.headers.get("Content-Type");
74
+ if (responseType === "blob") {
75
+ return await response.blob();
76
+ }
77
+ const isText = responseType === "text";
78
+ const isJson = contentType && contentType.includes("application/json");
79
+ if (isJson && !isText) {
80
+ return await response.json();
81
+ } else if (isTextForContentType(contentType)) {
82
+ return {
83
+ code: response.status,
84
+ status: response.status,
85
+ data: await response.text()
86
+ };
87
+ } else {
88
+ return response;
89
+ }
90
+ }).catch((err) => {
91
+ if (err.name === "AbortError") {
92
+ return {
93
+ code: 408,
94
+ message: "请求超时"
95
+ };
96
+ }
97
+ return {
98
+ code: 500,
99
+ message: err.message || "网络错误"
100
+ };
101
+ }).finally(() => {
102
+ clearTimeout(timer);
103
+ });
104
+ };
105
+ var wrapperError = ({ code, message }) => {
106
+ const result = {
107
+ code: code || 500,
108
+ success: false,
109
+ message: message || "api request error",
110
+ showError: (fn) => {},
111
+ noMsg: true
112
+ };
113
+ return result;
114
+ };
115
+
116
+ class Query {
117
+ adapter;
118
+ url;
119
+ beforeRequest;
120
+ afterResponse;
121
+ headers;
122
+ timeout;
123
+ stop;
124
+ qws;
125
+ isClient = false;
126
+ constructor(opts) {
127
+ this.adapter = opts?.adapter || adapter;
128
+ const defaultURL = opts?.isClient ? "/client/router" : "/api/router";
129
+ this.url = opts?.url || defaultURL;
130
+ this.headers = opts?.headers || {
131
+ "Content-Type": "application/json"
132
+ };
133
+ this.timeout = opts?.timeout || 60000 * 3;
134
+ if (opts.beforeRequest) {
135
+ this.beforeRequest = opts.beforeRequest;
136
+ } else {
137
+ this.beforeRequest = async (opts2) => {
138
+ const token = globalThis?.localStorage?.getItem("token");
139
+ if (token) {
140
+ opts2.headers = {
141
+ ...opts2.headers,
142
+ Authorization: `Bearer ${token}`
143
+ };
144
+ }
145
+ return opts2;
146
+ };
147
+ }
148
+ }
149
+ setQueryWs(qws) {
150
+ this.qws = qws;
151
+ }
152
+ setStop(stop) {
153
+ this.stop = stop;
154
+ }
155
+ async get(params, options) {
156
+ return this.post(params, options);
157
+ }
158
+ async post(body, options) {
159
+ const url = options?.url || this.url;
160
+ const { headers, adapter: adapter2, beforeRequest, afterResponse, timeout, ...rest } = options || {};
161
+ const _headers = { ...this.headers, ...headers };
162
+ const _adapter = adapter2 || this.adapter;
163
+ const _beforeRequest = beforeRequest || this.beforeRequest;
164
+ const _afterResponse = afterResponse || this.afterResponse;
165
+ const _timeout = timeout || this.timeout;
166
+ const req = {
167
+ url,
168
+ headers: _headers,
169
+ body,
170
+ timeout: _timeout,
171
+ ...rest
172
+ };
173
+ try {
174
+ if (_beforeRequest) {
175
+ const res = await _beforeRequest(req);
176
+ if (res === false) {
177
+ return wrapperError({
178
+ code: 500,
179
+ message: "request is cancel",
180
+ req
181
+ });
182
+ }
183
+ }
184
+ } catch (e) {
185
+ console.error("request beforeFn error", e, req);
186
+ return wrapperError({
187
+ code: 500,
188
+ message: "api request beforeFn error"
189
+ });
190
+ }
191
+ if (this.stop && !options?.noStop) {
192
+ const that = this;
193
+ await new Promise((resolve) => {
194
+ let timer = 0;
195
+ const detect = setInterval(() => {
196
+ if (!that.stop) {
197
+ clearInterval(detect);
198
+ resolve(true);
199
+ }
200
+ timer++;
201
+ if (timer > 30) {
202
+ console.error("request stop: timeout", req.url, timer);
203
+ }
204
+ }, 1000);
205
+ });
206
+ }
207
+ return _adapter(req).then(async (res) => {
208
+ try {
209
+ if (_afterResponse) {
210
+ return await _afterResponse(res, {
211
+ req,
212
+ res,
213
+ fetch: adapter2
214
+ });
215
+ }
216
+ return res;
217
+ } catch (e) {
218
+ console.error("request afterFn error", e, req);
219
+ return wrapperError({
220
+ code: 500,
221
+ message: "api request afterFn error"
222
+ });
223
+ }
224
+ });
225
+ }
226
+ before(fn) {
227
+ this.beforeRequest = fn;
228
+ }
229
+ after(fn) {
230
+ this.afterResponse = fn;
231
+ }
232
+ async fetchText(urlOrOptions, options) {
233
+ let _options = { ...options };
234
+ if (typeof urlOrOptions === "string" && !_options.url) {
235
+ _options.url = urlOrOptions;
236
+ }
237
+ if (typeof urlOrOptions === "object") {
238
+ _options = { ...urlOrOptions, ..._options };
239
+ }
240
+ const res = await adapter({
241
+ method: "GET",
242
+ ..._options,
243
+ headers: {
244
+ ...this.headers,
245
+ ..._options?.headers || {}
246
+ }
247
+ });
248
+ if (res && !res.code) {
249
+ return {
250
+ code: 200,
251
+ data: res
252
+ };
253
+ }
254
+ return res;
255
+ }
256
+ }
257
+
258
+ // query/query-config/query-config.ts
259
+ var defaultConfigKeys = ["upload.json", "workspace.json", "ai.json", "user.json", "life.json"];
260
+
261
+ class QueryConfig {
262
+ query;
263
+ constructor(opts) {
264
+ this.query = opts?.query || new Query;
265
+ }
266
+ async post(data) {
267
+ return this.query.post({ path: "config", ...data });
268
+ }
269
+ async getConfig({ id, key }, opts) {
270
+ return this.post({
271
+ key: "get",
272
+ data: {
273
+ id,
274
+ key
275
+ },
276
+ ...opts
277
+ });
278
+ }
279
+ async updateConfig(data, opts) {
280
+ return this.post({
281
+ key: "update",
282
+ data,
283
+ ...opts
284
+ });
285
+ }
286
+ async deleteConfig(data, opts) {
287
+ console.log("Delete Config Params:", data);
288
+ return this.post({
289
+ key: "delete",
290
+ data
291
+ });
292
+ }
293
+ async listConfig(opts) {
294
+ return this.post({
295
+ key: "list",
296
+ ...opts
297
+ });
298
+ }
299
+ async getUploadConfig(opts) {
300
+ return this.post({
301
+ key: "getUploadConfig",
302
+ ...opts
303
+ });
304
+ }
305
+ async updateUploadConfig(data, opts) {
306
+ return this.post({
307
+ key: "updateUploadConfig",
308
+ data,
309
+ ...opts
310
+ });
311
+ }
312
+ async detectConfig(opts) {
313
+ return this.post({
314
+ key: "detect",
315
+ ...opts
316
+ });
317
+ }
318
+ async getConfigByKey(key, opts) {
319
+ return this.post({
320
+ key: "defaultConfig",
321
+ configKey: key,
322
+ ...opts
323
+ });
324
+ }
325
+ async getByKey(key, opts) {
326
+ return this.post({
327
+ key: "get",
328
+ ...opts,
329
+ data: { key }
330
+ });
331
+ }
332
+ }
333
+ export {
334
+ defaultConfigKeys,
335
+ QueryConfig
336
+ };
@@ -0,0 +1,299 @@
1
+ import { BaseQuery, Query } from '@kevisual/query';
2
+ import { DataOpts, Result } from '@kevisual/query/query';
3
+
4
+ interface Cache {
5
+ /**
6
+ * @update 获取缓存
7
+ */
8
+ get(key: string): Promise<any>;
9
+ /**
10
+ * @update 设置缓存
11
+ */
12
+ set(key: string, value: any): Promise<any>;
13
+ /**
14
+ * @update 删除缓存
15
+ */
16
+ del(): Promise<void>;
17
+ /**
18
+ * 初始化
19
+ */
20
+ init?: () => Promise<any>;
21
+ }
22
+ type User = {
23
+ avatar?: string;
24
+ description?: string;
25
+ id?: string;
26
+ needChangePassword?: boolean;
27
+ orgs?: string[];
28
+ type?: string;
29
+ username?: string;
30
+ };
31
+ type CacheLoginUser = {
32
+ user?: User;
33
+ id?: string;
34
+ accessToken?: string;
35
+ refreshToken?: string;
36
+ };
37
+ type CacheLogin = {
38
+ loginUsers: CacheLoginUser[];
39
+ } & CacheLoginUser;
40
+ type CacheStore<T = Cache> = {
41
+ name: string;
42
+ /**
43
+ * 缓存数据
44
+ * @important 需要先调用init
45
+ */
46
+ cacheData: CacheLogin;
47
+ /**
48
+ * 实际操作的cache, 需要先调用init
49
+ */
50
+ cache: T;
51
+ /**
52
+ * 设置当前用户
53
+ */
54
+ setLoginUser(user: CacheLoginUser): Promise<void>;
55
+ /**
56
+ * 获取当前用户
57
+ */
58
+ getCurrentUser(): Promise<User>;
59
+ /**
60
+ * 获取当前用户列表
61
+ */
62
+ getCurrentUserList(): Promise<CacheLoginUser[]>;
63
+ /**
64
+ * 获取缓存的refreshToken
65
+ */
66
+ getRefreshToken(): Promise<string>;
67
+ /**
68
+ * 获取缓存的accessToken
69
+ */
70
+ getAccessToken(): Promise<string>;
71
+ /**
72
+ * 清除当前用户
73
+ */
74
+ clearCurrentUser(): Promise<void>;
75
+ /**
76
+ * 清除所有用户
77
+ */
78
+ clearAll(): Promise<void>;
79
+ getValue(): Promise<CacheLogin>;
80
+ setValue(value: CacheLogin): Promise<CacheLogin>;
81
+ delValue(): Promise<void>;
82
+ init(): Promise<any>;
83
+ };
84
+
85
+ type QueryLoginOpts = {
86
+ query?: Query;
87
+ isBrowser?: boolean;
88
+ onLoad?: () => void;
89
+ storage?: Storage;
90
+ cache: Cache;
91
+ };
92
+ type QueryLoginData = {
93
+ username?: string;
94
+ password: string;
95
+ email?: string;
96
+ };
97
+ type QueryLoginResult = {
98
+ accessToken: string;
99
+ refreshToken: string;
100
+ };
101
+ declare class QueryLogin extends BaseQuery {
102
+ /**
103
+ * query login cache, 非实际操作, 一个cache的包裹模块
104
+ */
105
+ cacheStore: CacheStore;
106
+ isBrowser: boolean;
107
+ load?: boolean;
108
+ storage: Storage;
109
+ onLoad?: () => void;
110
+ constructor(opts?: QueryLoginOpts);
111
+ setQuery(query: Query): void;
112
+ private init;
113
+ post<T = any>(data: any, opts?: DataOpts): Promise<any>;
114
+ /**
115
+ * 登录,
116
+ * @param data
117
+ * @returns
118
+ */
119
+ login(data: QueryLoginData): Promise<any>;
120
+ /**
121
+ * 手机号登录
122
+ * @param data
123
+ * @returns
124
+ */
125
+ loginByCode(data: {
126
+ phone: string;
127
+ code: string;
128
+ }): Promise<any>;
129
+ /**
130
+ * 设置token
131
+ * @param token
132
+ */
133
+ setLoginToken(token: {
134
+ accessToken: string;
135
+ refreshToken: string;
136
+ }): Promise<void>;
137
+ loginByWechat(data: {
138
+ code: string;
139
+ }): Promise<any>;
140
+ /**
141
+ * 检测微信登录,登陆成功后,调用onSuccess,否则调用onError
142
+ * @param param0
143
+ */
144
+ checkWechat({ onSuccess, onError }: {
145
+ onSuccess?: (res: QueryLoginResult) => void;
146
+ onError?: (res: any) => void;
147
+ }): Promise<void>;
148
+ /**
149
+ * 登陆成功,需要获取用户信息进行缓存
150
+ * @param param0
151
+ */
152
+ beforeSetLoginUser({ accessToken, refreshToken, check401 }: {
153
+ accessToken?: string;
154
+ refreshToken?: string;
155
+ check401?: boolean;
156
+ }): Promise<void>;
157
+ /**
158
+ * 刷新token
159
+ * @param refreshToken
160
+ * @returns
161
+ */
162
+ queryRefreshToken(refreshToken?: string): Promise<any>;
163
+ /**
164
+ * 检查401错误,并刷新token, 如果refreshToken存在,则刷新token, 否则返回401
165
+ * 拦截请求,请使用run401Action, 不要直接使用 afterCheck401ToRefreshToken
166
+ * @param response
167
+ * @param ctx
168
+ * @param refetch
169
+ * @returns
170
+ */
171
+ afterCheck401ToRefreshToken(response: Result, ctx?: {
172
+ req?: any;
173
+ res?: any;
174
+ fetch?: any;
175
+ }, refetch?: boolean): Promise<any>;
176
+ /**
177
+ * 一个简单的401处理, 如果401,则刷新token, 如果refreshToken不存在,则返回401
178
+ * refetch 是否重新请求, 会有bug,无限循环,按需要使用
179
+ * TODO:
180
+ * @param response
181
+ * @param ctx
182
+ * @param opts
183
+ * @returns
184
+ */
185
+ run401Action(response: Result, ctx?: {
186
+ req?: any;
187
+ res?: any;
188
+ fetch?: any;
189
+ }, opts?: {
190
+ /**
191
+ * 是否重新请求, 会有bug,无限循环,按需要使用
192
+ */
193
+ refetch?: boolean;
194
+ /**
195
+ * check之后的回调
196
+ */
197
+ afterCheck?: (res: Result) => any;
198
+ /**
199
+ * 401处理后, 还是401, 则回调
200
+ */
201
+ afterAlso401?: (res: Result) => any;
202
+ }): Promise<any>;
203
+ /**
204
+ * 获取用户信息
205
+ * @param token
206
+ * @returns
207
+ */
208
+ getMe(token?: string, check401?: boolean): Promise<any>;
209
+ /**
210
+ * 检查本地用户,如果本地用户存在,则返回本地用户,否则返回null
211
+ * @returns
212
+ */
213
+ checkLocalUser(): Promise<{
214
+ avatar?: string;
215
+ description?: string;
216
+ id?: string;
217
+ needChangePassword?: boolean;
218
+ orgs?: string[];
219
+ type?: string;
220
+ username?: string;
221
+ }>;
222
+ /**
223
+ * 检查本地token是否存在,简单的判断是否已经属于登陆状态
224
+ * @returns
225
+ */
226
+ checkLocalToken(): Promise<boolean>;
227
+ /**
228
+ * 检查本地用户列表
229
+ * @returns
230
+ */
231
+ getToken(): Promise<string>;
232
+ beforeRequest(opts?: any): Promise<any>;
233
+ /**
234
+ * 请求更新,切换用户, 使用switchUser
235
+ * @param username
236
+ * @returns
237
+ */
238
+ private postSwitchUser;
239
+ /**
240
+ * 切换用户
241
+ * @param username
242
+ * @returns
243
+ */
244
+ switchUser(username: string): Promise<any>;
245
+ /**
246
+ * 退出登陆,去掉token, 并删除缓存
247
+ * @returns
248
+ */
249
+ logout(): Promise<any>;
250
+ /**
251
+ * 检查用户名的组,这个用户是否存在
252
+ * @param username
253
+ * @returns
254
+ */
255
+ hasUser(username: string): Promise<any>;
256
+ /**
257
+ * 检查登录状态
258
+ * @param token
259
+ * @returns
260
+ */
261
+ checkLoginStatus(token: string): Promise<any>;
262
+ /**
263
+ * 使用web登录,创建url地址, 需要MD5和jsonwebtoken
264
+ *
265
+ *
266
+
267
+ import MD5 from 'crypto-js/md5.js';
268
+ import jsonwebtoken from 'jsonwebtoken';
269
+
270
+ */
271
+ loginWithWeb(baseURL: string, { MD5, jsonwebtoken }: {
272
+ MD5?: any;
273
+ jsonwebtoken?: any;
274
+ }): {
275
+ url: string;
276
+ token: string;
277
+ tokenSecret: string;
278
+ };
279
+ /**
280
+ *轮询登录状态
281
+ *
282
+ *
283
+ *
284
+ const res = queryLogin.loginWithWeb(baseURL, { MD5, jsonwebtoken });
285
+ await pollLoginStatus(res.token, { tokenSecret: res.tokenSecret });
286
+ * 轮询登录状态
287
+ */
288
+ pollLoginStatus(data: {
289
+ token: string;
290
+ tokenSecret: string;
291
+ }): Promise<boolean>;
292
+ }
293
+
294
+ type QueryLoginNodeOptsWithoutCache = Omit<QueryLoginOpts, 'cache'>;
295
+ declare class QueryLoginBrowser extends QueryLogin {
296
+ constructor(opts: QueryLoginNodeOptsWithoutCache);
297
+ }
298
+
299
+ export { QueryLoginBrowser };