@skyfox2000/webui 1.4.1 → 1.4.3

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.
@@ -1,146 +1,167 @@
1
1
  /**
2
- * 子应用SDK - 提供统一的主应用API调用接口
2
+ * 微前端通信工具
3
+ * 提供与主应用的通信接口,基于micro-app框架
3
4
  */
4
5
 
5
- // 定义API方法类型
6
- interface MainApis {
7
- getAppInfo: () => Promise<any>;
8
- getHostInfo: () => Promise<any>;
9
- getUserInfo: () => Promise<any>;
10
- getToken: () => Promise<any>;
11
- userLogin: (params: any) => Promise<any>;
12
- userLogout: () => Promise<any>;
13
- mainAppPush: (params: any) => Promise<any>;
6
+ // 定义请求数据格式
7
+ interface ApiRequestData {
8
+ type: 'API_REQUEST';
9
+ id: number;
10
+ method: string;
11
+ params?: any;
14
12
  }
15
13
 
16
- // 定义可用的API方法名称
17
- type MainApiMethod = keyof MainApis;
14
+ // 定义响应数据格式
15
+ interface ApiResponseData {
16
+ type: 'API_RESPONSE';
17
+ id: number;
18
+ success: boolean;
19
+ result?: any;
20
+ error?: string;
21
+ }
18
22
 
19
- /**
20
- * MicroAppSDK类 - 管理与主应用的通信
21
- */
22
23
  class MicroAppSDK {
23
- constructor() {
24
- this.ensureMicroAppReady();
25
- }
26
-
27
- /**
28
- * 确保micro-app环境就绪
29
- */
30
- ensureMicroAppReady() {
31
- if (typeof window === 'undefined') {
32
- throw new Error('MicroAppSDK can only be used in browser environment');
33
- }
34
- }
35
-
36
- /**
37
- * 获取基座API
38
- */
39
- getMainApis(): Partial<MainApis> {
40
- if (this.isInMicroApp() && (window as any).microApp && (window as any).microApp.getData) {
41
- const data = (window as any).microApp.getData();
42
- return data?.MainApis || {};
43
- }
44
- return {};
45
- }
46
-
47
- /**
48
- * 检查是否在微前端环境中
49
- */
50
- isInMicroApp(): boolean {
51
- return !!(window as any).microApp;
52
- }
53
-
54
- /**
55
- * API调用包装器
56
- */
57
- async callMainApi<T extends MainApiMethod>(methodName: T, params?: any): Promise<ReturnType<MainApis[T]>> {
58
- const mainApis = this.getMainApis();
59
-
60
- // 使用类型断言解决TypeScript类型检查问题
61
- const method = mainApis[methodName] as Function | undefined;
62
-
63
- if (!method) {
64
- throw new Error(`Main API method '${methodName}' is not available`);
65
- }
66
-
67
- try {
68
- if (params !== undefined) {
69
- return await method(params);
70
- } else {
71
- return await method();
24
+ private static messageId = 0;
25
+ private static callbacks = new Map<number, { resolve: Function; reject: Function }>();
26
+
27
+ /**
28
+ * 检查是否在微前端环境中运行
29
+ * @returns boolean
30
+ */
31
+ static isInMicroApp(): boolean {
32
+ return typeof window !== 'undefined' && !!(window as any).microApp;
33
+ }
34
+
35
+ /**
36
+ * 调用主应用方法的通用方法
37
+ * @param method 方法名
38
+ * @param params 参数
39
+ * @returns Promise
40
+ */
41
+ private static async callMainAppMethod(method: string, params?: any): Promise<any> {
42
+ // 检查是否在微前端环境中
43
+ if (!this.isInMicroApp()) {
44
+ throw new Error(`未配置${method}接口!`);
72
45
  }
73
- } catch (error) {
74
- console.error(`Failed to call main API '${methodName}':`, error);
75
- throw error;
76
- }
77
- }
78
-
79
- /**
80
- * 获取应用信息
81
- */
82
- async getAppInfo(): Promise<any> {
83
- return this.callMainApi('getAppInfo');
84
- }
85
-
86
- /**
87
- * 获取主机信息
88
- */
89
- async getHostInfo(): Promise<any> {
90
- return this.callMainApi('getHostInfo');
91
- }
92
-
93
- /**
94
- * 获取用户信息
95
- */
96
- async getUserInfo(): Promise<any> {
97
- return this.callMainApi('getUserInfo');
98
- }
99
-
100
- /**
101
- * 获取授权令牌
102
- */
103
- async getToken(): Promise<any> {
104
- return this.callMainApi('getToken');
105
- }
106
-
107
- /**
108
- * 用户登录
109
- */
110
- async userLogin(params: any): Promise<any> {
111
- return this.callMainApi('userLogin', params);
112
- }
113
-
114
- /**
115
- * 用户登出
116
- */
117
- async userLogout(): Promise<any> {
118
- return this.callMainApi('userLogout');
119
- }
120
-
121
- /**
122
- * 主应用推送
123
- */
124
- async mainAppPush(params: any): Promise<any> {
125
- return this.callMainApi('mainAppPush', params);
126
- }
127
- }
128
-
129
- // 创建单例实例
130
- const microAppSDKInstance = new MicroAppSDK();
131
46
 
132
- // 导出SDK实例和具体方法
133
- export default microAppSDKInstance;
134
-
135
- // 导出类和实例
136
- export { MicroAppSDK, microAppSDKInstance };
47
+ // 生成唯一消息ID
48
+ const id = ++this.messageId;
49
+
50
+ // 创建Promise并保存回调
51
+ const promise = new Promise((resolve, reject) => {
52
+ this.callbacks.set(id, { resolve, reject });
53
+
54
+ // 设置超时
55
+ setTimeout(() => {
56
+ if (this.callbacks.has(id)) {
57
+ this.callbacks.delete(id);
58
+ reject(new Error(`API调用超时: ${method}`));
59
+ }
60
+ }, 10000); // 10秒超时
61
+ });
62
+
63
+ // 构造请求数据
64
+ const requestData: ApiRequestData = {
65
+ type: 'API_REQUEST',
66
+ id,
67
+ method,
68
+ params,
69
+ };
70
+
71
+ // 发送数据到主应用(使用micro-app的dispatch方法)
72
+ (window as any).microApp.dispatch(requestData);
73
+
74
+ // 等待结果
75
+ return promise;
76
+ }
77
+
78
+ /**
79
+ * 处理来自主应用的响应数据
80
+ * @param data 响应数据
81
+ */
82
+ static handleResponseData(data: any) {
83
+ // 检查是否为API响应
84
+ if (data && data.type === 'API_RESPONSE' && typeof data.id === 'number') {
85
+ const { id, success, result, error } = data as ApiResponseData;
86
+ const callback = this.callbacks.get(id);
87
+
88
+ if (callback) {
89
+ this.callbacks.delete(id);
90
+ if (success) {
91
+ callback.resolve(result);
92
+ } else {
93
+ callback.reject(new Error(error || '未知错误'));
94
+ }
95
+ }
96
+ }
97
+ }
98
+
99
+ /**
100
+ * 初始化通信监听器
101
+ */
102
+ static init() {
103
+ if (this.isInMicroApp()) {
104
+ // 添加监听器
105
+ (window as any).microApp.addDataListener((data: any) => {
106
+ console.log('收到来自主应用的数据:', data);
107
+ this.handleResponseData(data);
108
+ });
109
+ }
110
+ }
111
+
112
+ /**
113
+ * 获取应用信息
114
+ */
115
+ static async getAppInfo(): Promise<any> {
116
+ return this.callMainAppMethod('getAppInfo');
117
+ }
118
+
119
+ /**
120
+ * 获取主机信息
121
+ */
122
+ static async getHostInfo(): Promise<any> {
123
+ return this.callMainAppMethod('getHostInfo');
124
+ }
125
+
126
+ /**
127
+ * 获取用户信息
128
+ */
129
+ static async getUserInfo(): Promise<any> {
130
+ return this.callMainAppMethod('getUserInfo');
131
+ }
132
+
133
+ /**
134
+ * 获取授权令牌
135
+ */
136
+ static async getToken(): Promise<any> {
137
+ return this.callMainAppMethod('getToken');
138
+ }
139
+
140
+ /**
141
+ * 用户登出
142
+ */
143
+ static async userLogout(): Promise<any> {
144
+ return this.callMainAppMethod('userLogout');
145
+ }
146
+
147
+ /**
148
+ * 主应用推送
149
+ */
150
+ static async mainAppPush(params: any): Promise<any> {
151
+ return this.callMainAppMethod('mainAppPush', params);
152
+ }
153
+ }
137
154
 
138
- // 导出所有方法
139
- export const getAppInfo = microAppSDKInstance.getAppInfo.bind(microAppSDKInstance);
140
- export const getHostInfo = microAppSDKInstance.getHostInfo.bind(microAppSDKInstance);
141
- export const getUserInfo = microAppSDKInstance.getUserInfo.bind(microAppSDKInstance);
142
- export const getToken = microAppSDKInstance.getToken.bind(microAppSDKInstance);
143
- export const userLogin = microAppSDKInstance.userLogin.bind(microAppSDKInstance);
144
- export const userLogout = microAppSDKInstance.userLogout.bind(microAppSDKInstance);
145
- export const mainAppPush = microAppSDKInstance.mainAppPush.bind(microAppSDKInstance);
146
- export const isInMicroApp = microAppSDKInstance.isInMicroApp.bind(microAppSDKInstance);
155
+ // 初始化通信监听器
156
+ MicroAppSDK.init();
157
+
158
+ // 导出统一对象
159
+ export const MicroOpenApis = {
160
+ getAppInfo: MicroAppSDK.getAppInfo.bind(MicroAppSDK),
161
+ getHostInfo: MicroAppSDK.getHostInfo.bind(MicroAppSDK),
162
+ getUserInfo: MicroAppSDK.getUserInfo.bind(MicroAppSDK),
163
+ getToken: MicroAppSDK.getToken.bind(MicroAppSDK),
164
+ userLogout: MicroAppSDK.userLogout.bind(MicroAppSDK),
165
+ mainAppPush: MicroAppSDK.mainAppPush.bind(MicroAppSDK),
166
+ isInMicroApp: MicroAppSDK.isInMicroApp.bind(MicroAppSDK),
167
+ };
@@ -1,204 +0,0 @@
1
- var m = Object.defineProperty;
2
- var E = (e, r, o) => r in e ? m(e, r, { enumerable: !0, configurable: !0, writable: !0, value: o }) : e[r] = o;
3
- var d = (e, r, o) => E(e, typeof r != "symbol" ? r + "" : r, o);
4
- import { hostUrl as v } from "@skyfox2000/fapi";
5
- import { af as S, ae as w, u as g } from "./uploadList-DIfhRlbh.js";
6
- import { mainAppApis as a } from "@skyfox2000/microbase";
7
- import y from "dayjs";
8
- import p from "vue-m-message";
9
- var i = /* @__PURE__ */ ((e) => (e.Pending = "pending", e.Uploading = "uploading", e.Success = "success", e.Error = "error", e.Online = "online", e.Offline = "offline", e))(i || {});
10
- const U = () => a.value ? a.value.getHostInfo() : S().hostInfo, x = () => a.value && a.value.getAppInfo ? a.value.getAppInfo() : w().appInfo, L = (e) => a.value && a.value.userLogin ? a.value.userLogin(e) : g().login(e, !0), M = () => a.value && a.value.userLogout ? a.value.userLogout() : g().logout(!0), b = () => a.value && a.value.getToken ? a.value.getToken() : g().getToken(), N = () => a.value && a.value.getUserInfo ? a.value.getUserInfo() : g().getUserInfo();
11
- class z {
12
- /**
13
- * 连接路径参数,已判断 undefined 或 null 值
14
- * @param args 路径参数数组
15
- * @returns 连接后的路径字符串
16
- */
17
- static join(...r) {
18
- return r.filter((u) => u != null).join("/").replace(/[\/]+/, "/");
19
- }
20
- }
21
- class C {
22
- /**
23
- * AsyncUploader 构造函数
24
- * @param urlInfo 文件上传的 API 配置(IUrlInfo 对象)
25
- * @param maxConcurrent 最大允许并发上传的文件数量
26
- */
27
- constructor(r, o = 3) {
28
- /**
29
- * 设置 API 端点和最大并发数,所有上传文件通过该类控制
30
- */
31
- d(this, "urlInfo");
32
- /**
33
- * 最大并发上传数
34
- */
35
- d(this, "maxConcurrent");
36
- /**
37
- * 控制上传任务的中断信号
38
- */
39
- d(this, "abortController");
40
- this.urlInfo = r, this.maxConcurrent = o;
41
- }
42
- /**
43
- * 执行上传
44
- * @param fileList 文件列表
45
- * @param loading 加载状态
46
- * @param continueOnError 错误时是否继续上传
47
- * @param onComplete 上传完成回调
48
- * @param onProgress 上传进度回调
49
- * @returns 上传结果
50
- */
51
- async doUpload(r, o, c, u, n) {
52
- if (r.length) {
53
- if (r.length === 0) {
54
- p.warning("请选择上传的文件!");
55
- return;
56
- }
57
- o.value = !0, await this.uploadFiles(r, n, (f) => {
58
- let t = !1, h = 0;
59
- for (const s of f)
60
- s.status === i.Error && h++;
61
- h ? h < f.length ? c ? (p.error("上传结束,部分文件上传失败!"), p.warning("保存上传成功的文件!"), t = !0) : p.error("上传结束,部分文件上传失败,取消保存!") : p.error("上传结束,所有文件上传失败!") : (p.success("全部文件上传成功!"), t = !0), o.value = !1, u == null || u(t, f);
62
- });
63
- }
64
- }
65
- /**
66
- * 上传多个文件,控制并发数量
67
- * @param files 文件列表(File[] 或 FileList)
68
- * @param onProgress 上传进度回调
69
- * @param onComplete 上传完成回调
70
- */
71
- async uploadFiles(r, o, c) {
72
- if (!r.length) return;
73
- const u = Math.min(this.maxConcurrent, r.length), n = [];
74
- for (const t of r)
75
- switch (t.status) {
76
- case i.Success:
77
- case i.Online:
78
- case i.Offline:
79
- break;
80
- default:
81
- t.status = i.Pending, n.push(t);
82
- break;
83
- }
84
- const f = [];
85
- this.abortController = new AbortController();
86
- try {
87
- for (; f.length < u && n.length > 0; ) {
88
- const t = n.shift();
89
- if (!t) break;
90
- f.push(this.handleFileStatus(t, f, n, o));
91
- }
92
- await Promise.all(f);
93
- } catch (t) {
94
- r.forEach((h) => {
95
- h.status = i.Error, h.error = t instanceof Error ? t : new Error("上传失败"), o == null || o(h);
96
- });
97
- } finally {
98
- c == null || c(r);
99
- }
100
- }
101
- /**
102
- * 处理单个文件的上传逻辑
103
- * @param file 当前上传的文件
104
- * @param activeUploads 当前正在上传的文件列表
105
- * @param pendingFiles 等待上传的文件列表
106
- * @param onProgress 上传进度回调
107
- */
108
- async handleFileStatus(r, o, c, u) {
109
- try {
110
- await this.uploadFile(r, this.abortController.signal, (n) => {
111
- r.percent = n, u == null || u(r);
112
- });
113
- } catch (n) {
114
- r.error = n instanceof Error ? n : new Error("上传失败");
115
- } finally {
116
- if (c.length > 0) {
117
- const n = c.shift();
118
- n && o.push(this.handleFileStatus(n, o, c, u));
119
- }
120
- }
121
- }
122
- /**
123
- * 使用 XMLHttpRequest 上传文件
124
- * @param file 文件对象
125
- * @param signal 中断信号
126
- * @param onProgress 上传进度回调
127
- */
128
- async uploadFile(r, o, c) {
129
- return r.status = i.Uploading, new Promise((u, n) => {
130
- const f = new FormData();
131
- if (f.append("file", r.originFileObj), r.params)
132
- for (const s in r.params)
133
- f.append(s, r.params[s]);
134
- const t = new XMLHttpRequest(), h = v(this.urlInfo);
135
- if (h === !1) return Promise.resolve(r);
136
- if (t.open("POST", h, !0), this.urlInfo.header && typeof this.urlInfo.header == "object" && Object.entries(this.urlInfo.header).forEach(([s, l]) => {
137
- t.setRequestHeader(s, l);
138
- }), this.urlInfo.authorize) {
139
- const s = b();
140
- if (!s) {
141
- n(new Error("未授权或授权过期"));
142
- return;
143
- }
144
- t.setRequestHeader("Authorization", "Bearer " + s);
145
- }
146
- t.upload.addEventListener("progress", (s) => {
147
- if (s.lengthComputable && s.total > 0) {
148
- const l = Math.round(s.loaded / s.total * 100);
149
- c(l);
150
- }
151
- }), t.addEventListener("load", () => {
152
- if (t.status >= 200 && t.status < 300) {
153
- const s = t.getResponseHeader("Content-Type");
154
- if (!s || !s.includes("application/json")) {
155
- n(new Error("返回的结果不是 JSON 格式"));
156
- return;
157
- }
158
- try {
159
- const l = JSON.parse(t.response);
160
- if (l.status === "success")
161
- l.data && (r.minioFile = {
162
- ETag: l.data.ETag,
163
- Bucket: l.data.Bucket,
164
- FileName: r.fileName,
165
- Key: l.data.Key,
166
- Size: l.data.Size,
167
- Type: r.type,
168
- UpdateTime: y().format("YYYY-MM-DD HH:mm:ss"),
169
- Status: i.Success
170
- }), r.status = i.Success, u(r);
171
- else {
172
- const I = l.msg;
173
- r.status = i.Error, n(new Error(I));
174
- }
175
- } catch (l) {
176
- r.status = i.Error, n(new Error("无法解析返回的 JSON 数据: " + l));
177
- }
178
- } else
179
- r.status = i.Error, n(new Error(`上传失败,状态码:${t.status}`));
180
- }), t.addEventListener("error", () => {
181
- r.status = i.Error, n(new Error("上传失败,网络异常"));
182
- }), t.send(f), o.addEventListener("abort", () => {
183
- t.abort(), n(new Error("上传已取消"));
184
- });
185
- });
186
- }
187
- /**
188
- * 取消当前所有的上传任务
189
- */
190
- cancelUpload() {
191
- this.abortController && this.abortController.abort();
192
- }
193
- }
194
- export {
195
- C as A,
196
- i as U,
197
- x as a,
198
- M as b,
199
- b as c,
200
- N as d,
201
- U as g,
202
- z as p,
203
- L as u
204
- };