@workopilot/webapp-sdk 0.1.5 → 0.1.7

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.
package/README.md CHANGED
@@ -64,6 +64,9 @@ VITE_APP_STORE_SECURE_KEY=please-replace-me-with-your-own-key
64
64
  - 自动检查 JWT 是否过期。
65
65
  - 生产环境没有 token 时,通过 iframe `postMessage` 通知宿主重新登录。
66
66
  - 开发环境没有 token 时,自动请求 `{javaBasePath}/auth/code` 获取验证码配置并弹出登录窗口。
67
+ - 业务请求返回 HTTP 401 时,清理失效 token;生产环境调用 `window.parent.location.reload()` 刷新父页面,并发送 `RELOGIN_REQUIRED` 消息及触发 `onReloginRequired`(`reason: 'unauthorized'`)。跨域限制导致刷新失败时,由宿主响应消息或回调处理重新登录。
68
+ - 开发环境收到 HTTP 401 时复用现有登录窗口,登录成功后保存新 token。并发请求共享同一次登录;生产环境同一 SDK 实例只触发一次刷新。
69
+ - 收到 401 的业务请求仍按失败返回,不自动重试;登录成功后,后续请求使用新 token。验证码和登录接口本身失败时直接报错,不递归弹出登录窗口。
67
70
  - 根据 `captchaEnabled` 决定是否显示验证码。
68
71
  - 登录接口默认使用 `POST {javaBasePath}/auth/login`,请求体不包含 `appCode`。
69
72
  - 支持按参考项目规则使用 AES + RSA 加密登录请求。
@@ -92,6 +95,25 @@ const data = await sdk.request('/some/api', {
92
95
 
93
96
  支持 `get`、`postJson` 和泛化 `request`。泛化请求支持自定义接口前缀、请求方法、查询参数、请求体类型和请求头。
94
97
 
98
+ ### 接口错误信息(0.1.7 起)
99
+
100
+ HTTP 非 2xx 响应优先使用 JSON 中的 `error.message`、`data.message`、`message`、`msg` 作为错误消息,忽略空值和非字符串。非 HTML 纯文本最多展示前 300 个字符;没有可用文案时显示 `请求失败(HTTP 状态码)`。业务接口、文件上传下载、流式请求以及开发登录和验证码接口均适用。
101
+
102
+ 抛出的 `WiseAiHttpError` 继承 `Error`,可以直接通过 `error.message` 展示后端错误,同时通过 `error.status` 和 `error.body` 获取状态码和响应内容。错误响应最多读取 64 KiB,超限后取消剩余响应体。401 重新登录行为保持不变,业务请求不自动重试。
103
+
104
+ ```ts
105
+ import { WiseAiHttpError } from '@workopilot/webapp-sdk';
106
+
107
+ try {
108
+ await sdk.postJson('/orders/save', { id: 'order-id' });
109
+ } catch (error) {
110
+ if (error instanceof WiseAiHttpError) {
111
+ // 例如:error.message 为“当前订单已关闭,无法修改”。
112
+ showError(error.message);
113
+ }
114
+ }
115
+ ```
116
+
95
117
  ### 文件上传
96
118
 
97
119
  ```ts
@@ -0,0 +1,8 @@
1
+ /** 保留接口状态码和响应内容,message 可直接用于页面错误提示。 */
2
+ export declare class WiseAiHttpError extends Error {
3
+ readonly status: number;
4
+ readonly body: unknown;
5
+ constructor(message: string, status: number, body: unknown);
6
+ }
7
+ /** 读取非成功响应;错误体不可读或没有错误文案时保留 HTTP 状态码。 */
8
+ export declare function createHttpError(response: Response): Promise<WiseAiHttpError>;
@@ -0,0 +1,93 @@
1
+ const MAX_ERROR_BODY_BYTES = 64 * 1024;
2
+ const MAX_TEXT_MESSAGE_LENGTH = 300;
3
+ /** 保留接口状态码和响应内容,message 可直接用于页面错误提示。 */
4
+ export class WiseAiHttpError extends Error {
5
+ constructor(message, status, body) {
6
+ super(message);
7
+ this.name = 'WiseAiHttpError';
8
+ this.status = status;
9
+ this.body = body;
10
+ }
11
+ }
12
+ function asRecord(value) {
13
+ if (value && typeof value === 'object' && !Array.isArray(value)) {
14
+ return value;
15
+ }
16
+ return undefined;
17
+ }
18
+ function getJsonMessage(body) {
19
+ const record = asRecord(body);
20
+ const candidates = [
21
+ asRecord(record?.error)?.message,
22
+ asRecord(record?.data)?.message,
23
+ record?.message,
24
+ record?.msg,
25
+ ];
26
+ for (const value of candidates) {
27
+ if (typeof value === 'string' && value.trim()) {
28
+ return value.trim();
29
+ }
30
+ }
31
+ return undefined;
32
+ }
33
+ async function readErrorText(response) {
34
+ if (!response.body) {
35
+ return '';
36
+ }
37
+ const reader = response.body.getReader();
38
+ const decoder = new TextDecoder();
39
+ let remaining = MAX_ERROR_BODY_BYTES;
40
+ let text = '';
41
+ let complete = false;
42
+ try {
43
+ while (remaining > 0) {
44
+ const { done, value } = await reader.read();
45
+ if (done) {
46
+ complete = true;
47
+ break;
48
+ }
49
+ const chunk = value.subarray(0, remaining);
50
+ text += decoder.decode(chunk, { stream: true });
51
+ remaining -= chunk.byteLength;
52
+ }
53
+ return text + decoder.decode();
54
+ }
55
+ finally {
56
+ try {
57
+ if (!complete) {
58
+ await reader.cancel();
59
+ }
60
+ }
61
+ finally {
62
+ reader.releaseLock();
63
+ }
64
+ }
65
+ }
66
+ /** 读取非成功响应;错误体不可读或没有错误文案时保留 HTTP 状态码。 */
67
+ export async function createHttpError(response) {
68
+ let body;
69
+ let message;
70
+ try {
71
+ const text = (await readErrorText(response)).trim();
72
+ if (text) {
73
+ try {
74
+ body = JSON.parse(text);
75
+ message = getJsonMessage(body);
76
+ }
77
+ catch {
78
+ body = text;
79
+ const contentType = response.headers.get('content-type') || '';
80
+ const isText = !contentType || /text\/|json/i.test(contentType);
81
+ const isHtml = /html/i.test(contentType) || /<(?:!doctype|\/?[a-z])[^>]*>/i.test(text);
82
+ const looksLikeJson = text.startsWith('{') || text.startsWith('[');
83
+ if (isText && !isHtml && !looksLikeJson) {
84
+ message = text.slice(0, MAX_TEXT_MESSAGE_LENGTH);
85
+ }
86
+ }
87
+ }
88
+ }
89
+ catch {
90
+ // 响应体读取失败也不能掩盖 HTTP 错误或阻止 401 重新登录。
91
+ }
92
+ return new WiseAiHttpError(message || `请求失败(HTTP ${response.status})`, response.status, body);
93
+ }
package/dist/http.d.ts CHANGED
@@ -24,11 +24,16 @@ export declare class WiseAiFrontSdk {
24
24
  private readonly routePermissionPath;
25
25
  private readonly loginRequest?;
26
26
  private accessToken;
27
+ private loginPromise?;
28
+ private parentReloadRequested;
29
+ private readonly rejectedTokens;
27
30
  constructor(options: WiseAiFrontSdkOptions);
28
31
  get state(): WiseAiFrontSdkState;
29
32
  private getCurrentToken;
30
33
  private ensureToken;
31
34
  private loginInDev;
35
+ private handleUnauthorized;
36
+ private performDevLogin;
32
37
  private buildLoginRequest;
33
38
  private openLoginModal;
34
39
  private fetchCaptchaConfig;
package/dist/http.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import { fetchManagedResponse, getDownloadFilename, readResponse } from './response-stream';
2
+ import { createHttpError } from './http-error';
2
3
  import { notifyReloginRequired, } from './bridge';
3
4
  import { encryptRequestBody, } from './encryption';
4
5
  import { isJwtExpired, } from './jwt';
@@ -78,6 +79,8 @@ function unwrapEnvelope(body) {
78
79
  }
79
80
  export class WiseAiFrontSdk {
80
81
  constructor(options) {
82
+ this.parentReloadRequested = false;
83
+ this.rejectedTokens = new Set();
81
84
  this.accessToken = options.accessToken?.trim() || '';
82
85
  this.appCode = options.appCode;
83
86
  this.captchaPath = options.captchaPath || '/auth/code';
@@ -127,7 +130,7 @@ export class WiseAiFrontSdk {
127
130
  ...resolveTokensFromSecureStore(this.storage, this.secureStoreKey, this.secureStoreNamespace),
128
131
  ];
129
132
  for (const token of candidates) {
130
- if (token && !isJwtExpired(token)) {
133
+ if (token && !this.rejectedTokens.has(token) && !isJwtExpired(token)) {
131
134
  return token;
132
135
  }
133
136
  }
@@ -135,6 +138,12 @@ export class WiseAiFrontSdk {
135
138
  return '';
136
139
  }
137
140
  async ensureToken() {
141
+ if (this.loginPromise) {
142
+ return this.loginPromise;
143
+ }
144
+ if (this.parentReloadRequested) {
145
+ throw new Error('WiseAiFrontSDK: relogin required in prod environment');
146
+ }
138
147
  const current = await this.getCurrentToken();
139
148
  if (current) {
140
149
  this.accessToken = current;
@@ -154,6 +163,50 @@ export class WiseAiFrontSdk {
154
163
  return token;
155
164
  }
156
165
  async loginInDev() {
166
+ if (!this.loginPromise) {
167
+ this.loginPromise = this.performDevLogin()
168
+ .then((token) => {
169
+ this.accessToken = token;
170
+ this.rejectedTokens.delete(token);
171
+ return token;
172
+ })
173
+ .finally(() => {
174
+ this.loginPromise = undefined;
175
+ });
176
+ }
177
+ return this.loginPromise;
178
+ }
179
+ async handleUnauthorized(token) {
180
+ if (this.loginPromise) {
181
+ await this.loginPromise;
182
+ return;
183
+ }
184
+ // 忽略旧请求迟到的 401,避免清除重新登录后取得的 token。
185
+ if (this.accessToken !== token || this.parentReloadRequested) {
186
+ return;
187
+ }
188
+ this.rejectedTokens.add(token);
189
+ this.clearToken();
190
+ if (this.env === 'dev') {
191
+ await this.loginInDev();
192
+ return;
193
+ }
194
+ this.parentReloadRequested = true;
195
+ try {
196
+ // 默认 parentWindow 为 window.parent;跨域时由宿主消息处理兜底。
197
+ this.parentWindow?.location.reload();
198
+ }
199
+ catch {
200
+ // 浏览器同源策略可能禁止 iframe 直接刷新父页面。
201
+ }
202
+ notifyReloginRequired(this.parentWindow, this.appCode, this.env, 'unauthorized');
203
+ this.onReloginRequired?.({
204
+ appCode: this.appCode,
205
+ env: this.env,
206
+ reason: 'unauthorized',
207
+ });
208
+ }
209
+ async performDevLogin() {
157
210
  if (this.loginRequest) {
158
211
  const result = await this.loginRequest(await this.openLoginModal());
159
212
  const token = result.access_token || result.accessToken || '';
@@ -179,7 +232,7 @@ export class WiseAiFrontSdk {
179
232
  method: 'POST',
180
233
  });
181
234
  if (!response.ok) {
182
- throw new Error(`WiseAiFrontSDK: login failed with ${response.status}`);
235
+ throw await createHttpError(response);
183
236
  }
184
237
  const data = (await response.json());
185
238
  const loginResult = unwrapEnvelope(data);
@@ -234,7 +287,7 @@ export class WiseAiFrontSdk {
234
287
  method: 'GET',
235
288
  });
236
289
  if (!response.ok) {
237
- throw new Error(`WiseAiFrontSDK: captcha request failed with ${response.status}`);
290
+ throw await createHttpError(response);
238
291
  }
239
292
  const body = (await response.json());
240
293
  return unwrapEnvelope(body);
@@ -273,8 +326,11 @@ export class WiseAiFrontSdk {
273
326
  signal: options.signal,
274
327
  }, options.timeoutMs ?? this.requestTimeoutMs);
275
328
  if (!response.ok) {
276
- await response.body?.cancel();
277
- throw new Error(`WiseAiFrontSDK: request failed with ${response.status}`);
329
+ const error = await createHttpError(response);
330
+ if (response.status === 401) {
331
+ await this.handleUnauthorized(token);
332
+ }
333
+ throw error;
278
334
  }
279
335
  return readResponse(response, options.responseType);
280
336
  }
package/dist/index.d.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  export { decodeJwtPayload, isJwtExpired } from './jwt';
2
2
  export { notifyReloginRequired } from './bridge';
3
+ export { WiseAiHttpError } from './http-error';
3
4
  import { WiseAiFrontSdk } from './http';
4
5
  export { persistToken, resolveTokenFromLocation, resolveTokenFromStorage, resolveTokensFromSecureStore, } from './storage';
5
6
  export type { ApiBase, DownloadResult, HttpMethod, JwtPayload, LoginCredentials, LoginModalOptions, LoginResult, MenuPermissionNode, MenuRouteMeta, RequestBodyType, RequestOptions, UploadOptions, WiseAiEnvironment, WiseAiFrontSdkOptions, WiseAiFrontSdkState, } from './types';
package/dist/index.js CHANGED
@@ -1,5 +1,6 @@
1
1
  export { decodeJwtPayload, isJwtExpired } from './jwt';
2
2
  export { notifyReloginRequired } from './bridge';
3
+ export { WiseAiHttpError } from './http-error';
3
4
  import { WiseAiFrontSdk } from './http';
4
5
  export { persistToken, resolveTokenFromLocation, resolveTokenFromStorage, resolveTokensFromSecureStore, } from './storage';
5
6
  export { WiseAiFrontSdk } from './http';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@workopilot/webapp-sdk",
3
- "version": "0.1.5",
3
+ "version": "0.1.7",
4
4
  "description": "WiseAI front-end SDK for iframe-hosted third-party apps",
5
5
  "keywords": "wiseai,workopilot",
6
6
  "author": "workopilot",