@lark-apaas/client-toolkit 1.2.82 → 1.2.83-alpha.20261106064810

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.
@@ -6,9 +6,6 @@ import { normalizeBasePath } from "../../utils/utils.js";
6
6
  function PageHoc({ children }) {
7
7
  useEffect(()=>{
8
8
  if ('development' !== process.env.NODE_ENV) return;
9
- try {
10
- if ('workmate' === process.env.MIAODA_APP_CREATED_VIA) return;
11
- } catch {}
12
9
  let cancelled = false;
13
10
  const basePath = normalizeBasePath(process.env.CLIENT_BASE_PATH);
14
11
  const id = networkIdleCallback(()=>{
@@ -1,5 +1,4 @@
1
1
  import { Fragment, jsx, jsxs } from "react/jsx-runtime";
2
- import { getWatermarkVariant, readWatermarkCreatedVia } from "./watermark-variant.js";
3
2
  import { useEffect, useRef, useState } from "react";
4
3
  import { Content, Portal, Root, Trigger } from "@radix-ui/react-popover";
5
4
  import { DOUBAO_BRAND_TEXT_SRC, DOUBAO_LOGO_SRC, MIAODA_LOGO_SRC } from "./doubao-watermark-asset.js";
@@ -7,7 +6,8 @@ import { getAppId } from "../../utils/getAppId.js";
7
6
  import { getEnv } from "../../utils/getParentOrigin.js";
8
7
  import { getInitialInfo } from "../../utils/getInitialInfo.js";
9
8
  import { useIsMobile } from "../../hooks/index.js";
10
- const VARIANT = getWatermarkVariant(process.env.MIAODA_APP_SOURCE, readWatermarkCreatedVia());
9
+ const DOUBAO_SOURCE = '5';
10
+ const VARIANT = String(process.env.MIAODA_APP_SOURCE) === DOUBAO_SOURCE ? 'doubao' : 'miaoda';
11
11
  const VARIANT_CONFIG = {
12
12
  doubao: {
13
13
  brandText: '豆包工作 AI 生成',
@@ -46,7 +46,6 @@ beforeEach(()=>{
46
46
  vi.useFakeTimers();
47
47
  vi.clearAllMocks();
48
48
  vi.stubEnv('NODE_ENV', 'development');
49
- vi.stubEnv('MIAODA_APP_CREATED_VIA', void 0);
50
49
  vi.stubEnv('CLIENT_BASE_PATH', '/app/test/');
51
50
  globalThis.IS_REACT_ACT_ENVIRONMENT = true;
52
51
  container = document.createElement('div');
@@ -103,53 +102,6 @@ describe('development page screenshot', ()=>{
103
102
  expect(snapdom).not.toHaveBeenCalled();
104
103
  expect(submitPostMessage).not.toHaveBeenCalled();
105
104
  });
106
- it('does not schedule or capture for workmate applications', async ()=>{
107
- vi.stubEnv('MIAODA_APP_CREATED_VIA', 'workmate');
108
- await mount();
109
- await idle();
110
- expect(container.textContent).toBe('Application');
111
- expect(networkIdleCallback).not.toHaveBeenCalled();
112
- expect(snapdom).not.toHaveBeenCalled();
113
- expect(submitPostMessage).not.toHaveBeenCalled();
114
- });
115
- it.each([
116
- void 0,
117
- '',
118
- 'miaoda'
119
- ])('still captures for other creation sources: %s', async (source)=>{
120
- vi.stubEnv('MIAODA_APP_CREATED_VIA', source);
121
- await mount();
122
- await idle();
123
- expect(snapdom).toHaveBeenCalledTimes(1);
124
- expect(submitPostMessage).toHaveBeenCalledWith({
125
- type: 'PageScreenshot',
126
- data: png
127
- });
128
- });
129
- it('still captures when an older preset leaves the creation source unavailable', async ()=>{
130
- const originalProcess = process;
131
- const env = new Proxy(process.env, {
132
- get (target, key) {
133
- if ('MIAODA_APP_CREATED_VIA' === key) throw new ReferenceError('process is not defined');
134
- return Reflect.get(target, key);
135
- }
136
- });
137
- vi.stubGlobal('process', new Proxy(originalProcess, {
138
- get (target, key) {
139
- return 'env' === key ? env : Reflect.get(target, key);
140
- }
141
- }));
142
- try {
143
- await mount();
144
- await idle();
145
- } finally{
146
- vi.unstubAllGlobals();
147
- }
148
- expect(submitPostMessage).toHaveBeenCalledWith({
149
- type: 'PageScreenshot',
150
- data: png
151
- });
152
- });
153
105
  it('only schedules one active capture under StrictMode', async ()=>{
154
106
  await mount(true);
155
107
  await idle();
@@ -6,7 +6,7 @@ async function getAppInfo(refresh = false) {
6
6
  const info = (await getInitialInfo(refresh))?.app_info;
7
7
  appInfo = {
8
8
  name: info?.app_name || '',
9
- avatar: normalizeAvatar(info?.app_avatar),
9
+ avatar: info?.app_avatar || '',
10
10
  description: info?.app_description || ''
11
11
  };
12
12
  if (appInfo.name) appInfo.name = appInfo.name.trim();
@@ -14,14 +14,4 @@ async function getAppInfo(refresh = false) {
14
14
  }
15
15
  return appInfo ?? {};
16
16
  }
17
- function normalizeAvatar(raw) {
18
- if (!raw) return '';
19
- if (raw.trim().startsWith('{')) try {
20
- const url = JSON.parse(raw)?.url;
21
- return 'string' == typeof url ? url : '';
22
- } catch {
23
- return '';
24
- }
25
- return raw;
26
- }
27
17
  export { getAppInfo };
@@ -3,6 +3,13 @@ import "../utils/utils.js";
3
3
  import { mappingText } from "./source-map-mappings-wasm.js";
4
4
  import stacktrace_js from "stacktrace-js";
5
5
  import { batchLogInfo } from "./batch-logger.js";
6
+ import { createNestedAxiosErrorExpander, expandTopLevelAxiosError } from "../utils/log-sanitize.js";
7
+ function serializeTopLevelError(error) {
8
+ return expandTopLevelAxiosError(error) ?? {
9
+ message: error.message,
10
+ stack: error.stack
11
+ };
12
+ }
6
13
  function getBrowserTransportLevel(level) {
7
14
  return 'success' === level ? 'info' : level;
8
15
  }
@@ -36,10 +43,7 @@ async function sendSelectedLog(logWithoutID) {
36
43
  const newParts = [];
37
44
  for(let i = 0; i < log.args.length; i++)if (log.args[i] instanceof Error) {
38
45
  const error = log.args[i];
39
- const newError = {
40
- message: error.message,
41
- stack: error.stack
42
- };
46
+ const newError = serializeTopLevelError(error);
43
47
  if (!log.meta.stacktrace) try {
44
48
  const stacktrace = await stacktrace_js.fromError(error);
45
49
  log.meta.stacktrace = mapStacktrace(stacktrace);
@@ -74,7 +78,10 @@ async function sendSelectedLog(logWithoutID) {
74
78
  } catch (postError) {}
75
79
  }
76
80
  if (void 0 === log.meta.skipFrame) log.meta.skipFrame = 2;
77
- const errorReplacer = (key, value)=>{
81
+ const expandNestedAxiosError = createNestedAxiosErrorExpander();
82
+ const errorReplacer = function(key, value) {
83
+ const expanded = expandNestedAxiosError(this?.[key]);
84
+ if (expanded) return expanded;
78
85
  if (value instanceof Error) return {
79
86
  message: value.message,
80
87
  stack: value.stack,
@@ -6,6 +6,7 @@ import { safeStringify } from "./safeStringify.js";
6
6
  import { slardar } from "@lark-apaas/internal-slardar";
7
7
  import { normalizeBasePath } from "./utils.js";
8
8
  import { t } from "../locales/index.js";
9
+ import { readHeader, sanitizeQueryParams, sanitizeRequestBody, sanitizeResponseBody } from "./log-sanitize.js";
9
10
  const APP_CLIENT_API_LOG_TYPE = 'app_client_api_log';
10
11
  function stripBasePath(urlPath) {
11
12
  const base = normalizeBasePath(process.env.CLIENT_BASE_PATH);
@@ -92,6 +93,20 @@ function getApiField(method, path) {
92
93
  return `${method} ${matched || path}`;
93
94
  }
94
95
  const isValidResponse = (resp)=>null != resp && 'object' == typeof resp && 'config' in resp && null !== resp.config && void 0 !== resp.config && 'object' == typeof resp.config && 'status' in resp && 'number' == typeof resp.status && 'data' in resp;
96
+ function sanitizedRequestFields(config, queryParams) {
97
+ try {
98
+ return {
99
+ 请求参数: sanitizeRequestBody(config.data, readHeader(config.headers, 'content-type')),
100
+ ...Object.keys(queryParams).length > 0 && {
101
+ 查询参数: sanitizeQueryParams(queryParams)
102
+ }
103
+ };
104
+ } catch {
105
+ return {
106
+ 请求参数: '[Unserializable]'
107
+ };
108
+ }
109
+ }
95
110
  async function logResponse(ok, responseOrError) {
96
111
  if (isValidResponse(responseOrError)) {
97
112
  const response = responseOrError;
@@ -123,11 +138,8 @@ async function logResponse(ok, responseOrError) {
123
138
  if (response.config.params) Object.assign(queryParams, response.config.params);
124
139
  const args = [
125
140
  {
126
- 请求参数: response.config.data,
127
- ...Object.keys(queryParams).length > 0 && {
128
- 查询参数: queryParams
129
- },
130
- 返回数据: response.data,
141
+ ...sanitizedRequestFields(response.config, queryParams),
142
+ 返回数据: sanitizeResponseBody(response.data),
131
143
  请求摘要: {
132
144
  方法: method,
133
145
  TraceID: logTraceID,
@@ -180,10 +192,7 @@ async function logResponse(ok, responseOrError) {
180
192
  if (error.config.params) Object.assign(queryParams, error.config.params);
181
193
  const args = [
182
194
  {
183
- 请求参数: error.config.data,
184
- ...Object.keys(queryParams).length > 0 && {
185
- 查询参数: queryParams
186
- },
195
+ ...sanitizedRequestFields(error.config, queryParams),
187
196
  错误信息: errorMessage,
188
197
  请求摘要: {
189
198
  方法: method,
@@ -0,0 +1,96 @@
1
+ /**
2
+ * @internal
3
+ * 开发态日志净化:把失败请求的上下文(URL、查询参数、请求体、响应体)脱敏并按体积预算裁剪后再上报。
4
+ *
5
+ * - 请求头一律不采集(只在解析请求体时读 Content-Type,不输出)。
6
+ * - 先还原结构:JSON 字符串请求体先解析,urlencoded 请求体按 query 规则逐键处理,其它字符串请求体只记类型和长度。
7
+ * - 脱敏:键名命中凭据模式时值替换为 [REDACTED];字符串值里的 Bearer / JWT 也替换。
8
+ * - 限体积:先保留结构地裁剪,仍超预算再降级为截断字符串(降级时保留顶层或 error 下的 code、message)。
9
+ * 预算按 JSON.stringify 后(即嵌入外层 JSON 时的转义后)长度计。
10
+ *
11
+ * client-toolkit-lite 维护一份逐字节相同的副本(包边界禁止跨包引用),只依赖两包都有的 ./utils。
12
+ */
13
+ export declare const REDACTED = "[REDACTED]";
14
+ export declare const LOG_SANITIZE_LIMITS: {
15
+ /** 请求 URL(去 origin、去 base path、query 已脱敏) */
16
+ readonly url: 300;
17
+ /** 查询参数对象 */
18
+ readonly params: 300;
19
+ /** 请求体 */
20
+ readonly requestBody: 400;
21
+ /** 响应体 */
22
+ readonly responseBody: 600;
23
+ /** 整段上下文 {request, response} */
24
+ readonly context: 1300;
25
+ };
26
+ /** 键名是否命中凭据类模式(不区分大小写,按词边界匹配) */
27
+ export declare function isSensitiveKey(key: string): boolean;
28
+ /** 替换字符串里的 Bearer 凭据、JWT,以及自由文本中凭据键对应的值 */
29
+ export declare function redactString(text: string): string;
30
+ /**
31
+ * 去掉 origin 与 base path 前缀,query 按凭据键名规则脱敏,并限制在 URL 预算内
32
+ */
33
+ export declare function sanitizeUrl(url: unknown, basePath?: string): string | undefined;
34
+ /** 查询参数对象(axios config.params 或从 URL 拆出的键值) */
35
+ export declare function sanitizeQueryParams(params: unknown, limit?: number): unknown;
36
+ /**
37
+ * 请求体:axios 发出前已把对象转成 JSON 字符串,先还原结构再脱敏裁剪。
38
+ * 无法解析的字符串不原样带出,只记类型和长度。
39
+ */
40
+ export declare function sanitizeRequestBody(data: unknown, contentType?: string, limit?: number): unknown;
41
+ /** 响应体:非 JSON 字符串(如 HTML 错误页)保留前 300 字符并做值模式替换 */
42
+ export declare function sanitizeResponseBody(data: unknown, limit?: number): unknown;
43
+ /** 读取单个请求/响应头(兼容普通对象与 AxiosHeaders);只用于解析,不输出 */
44
+ export declare function readHeader(headers: unknown, name: string): string | undefined;
45
+ export interface AxiosErrorLike {
46
+ isAxiosError: true;
47
+ message: string;
48
+ name?: string;
49
+ code?: string;
50
+ status?: number;
51
+ stack?: string;
52
+ config: {
53
+ method?: string;
54
+ url?: string;
55
+ params?: unknown;
56
+ data?: unknown;
57
+ headers?: unknown;
58
+ };
59
+ response?: {
60
+ status?: number;
61
+ statusText?: string;
62
+ headers?: unknown;
63
+ data?: unknown;
64
+ };
65
+ }
66
+ /** 鸭子类型识别 AxiosError(兼容应用自带的另一份 axios) */
67
+ export declare function isAxiosErrorLike(value: unknown): value is AxiosErrorLike;
68
+ type RequestContext = {
69
+ method: string;
70
+ url?: string;
71
+ params?: unknown;
72
+ data?: unknown;
73
+ };
74
+ type ResponseContext = {
75
+ status?: number;
76
+ statusText?: string;
77
+ traceId?: string;
78
+ data?: unknown;
79
+ };
80
+ /** 构造失败请求的上下文 {request, response},整段不超过 context 预算 */
81
+ export declare function buildAxiosErrorContext(error: AxiosErrorLike, basePath?: string): {
82
+ request: RequestContext;
83
+ response?: ResponseContext;
84
+ };
85
+ /**
86
+ * sendSelectedLog 顶层参数用:开发态且是 AxiosError 时返回 {message, request, response, axiosCode, stack};
87
+ * 生产态、非 AxiosError 或序列化出错时返回 undefined,由调用方回退到原有形态。NODE_ENV 在调用时读取。
88
+ */
89
+ export declare function expandTopLevelAxiosError(error: unknown): Record<string, unknown> | undefined;
90
+ /**
91
+ * sendSelectedLog 的 JSON.stringify replacer 用:返回一个按原始 AxiosError 缓存结果的展开函数。
92
+ * 去重逻辑会对同一条日志 stringify 多次,缓存保证每个 AxiosError 只净化一次;
93
+ * 生产态、非 AxiosError 或出错时返回 undefined,由调用方回退到原有形态。
94
+ */
95
+ export declare function createNestedAxiosErrorExpander(): (raw: unknown) => Record<string, unknown> | undefined;
96
+ export {};
@@ -0,0 +1,611 @@
1
+ import { normalizeBasePath } from "./utils.js";
2
+ const REDACTED = '[REDACTED]';
3
+ const LOG_SANITIZE_LIMITS = {
4
+ url: 300,
5
+ params: 300,
6
+ requestBody: 400,
7
+ responseBody: 600,
8
+ context: 1300
9
+ };
10
+ const TRIM_LEVELS = [
11
+ {
12
+ maxDepth: 4,
13
+ maxKeys: 30,
14
+ maxArrayItems: 10,
15
+ maxStringLength: 300
16
+ },
17
+ {
18
+ maxDepth: 4,
19
+ maxKeys: 30,
20
+ maxArrayItems: 10,
21
+ maxStringLength: 120
22
+ },
23
+ {
24
+ maxDepth: 4,
25
+ maxKeys: 20,
26
+ maxArrayItems: 5,
27
+ maxStringLength: 80
28
+ },
29
+ {
30
+ maxDepth: 4,
31
+ maxKeys: 15,
32
+ maxArrayItems: 5,
33
+ maxStringLength: 40
34
+ },
35
+ {
36
+ maxDepth: 3,
37
+ maxKeys: 10,
38
+ maxArrayItems: 3,
39
+ maxStringLength: 40
40
+ },
41
+ {
42
+ maxDepth: 2,
43
+ maxKeys: 8,
44
+ maxArrayItems: 3,
45
+ maxStringLength: 30
46
+ }
47
+ ];
48
+ const MAX_TRIM_NODES = 500;
49
+ const BASE_LEVEL = TRIM_LEVELS[0];
50
+ const PRIORITY_KEYS = [
51
+ 'code',
52
+ 'message'
53
+ ];
54
+ const TOP_PRIORITY_KEYS = [
55
+ ...PRIORITY_KEYS,
56
+ 'error'
57
+ ];
58
+ const MIN_FIELD_BUDGET = 40;
59
+ const OMITTED = '[omitted: over budget]';
60
+ const SENSITIVE_WORDS = new Set([
61
+ 'authorization',
62
+ 'cookie',
63
+ 'cookies',
64
+ 'setcookie',
65
+ 'token',
66
+ 'tokens',
67
+ 'accesstoken',
68
+ 'refreshtoken',
69
+ 'idtoken',
70
+ 'csrftoken',
71
+ 'xsrftoken',
72
+ 'password',
73
+ 'passwords',
74
+ 'passwd',
75
+ 'pwd',
76
+ 'secret',
77
+ 'secrets',
78
+ 'clientsecret',
79
+ 'apikey',
80
+ 'accesskey',
81
+ 'privatekey',
82
+ 'secretkey',
83
+ 'credential',
84
+ 'credentials',
85
+ 'session',
86
+ 'sessions',
87
+ 'sessionid',
88
+ 'signature',
89
+ 'csrf',
90
+ 'xsrf',
91
+ 'jwt'
92
+ ]);
93
+ const SENSITIVE_WORD_PAIRS = [
94
+ [
95
+ 'api',
96
+ 'key'
97
+ ],
98
+ [
99
+ 'access',
100
+ 'key'
101
+ ],
102
+ [
103
+ 'private',
104
+ 'key'
105
+ ]
106
+ ];
107
+ function splitKeyWords(key) {
108
+ return key.replace(/([a-z0-9])([A-Z])/g, '$1 $2').replace(/([A-Z]+)([A-Z][a-z])/g, '$1 $2').toLowerCase().split(/[^a-z0-9]+/).filter(Boolean);
109
+ }
110
+ function isSensitiveKey(key) {
111
+ const words = splitKeyWords(key);
112
+ if (0 === words.length) return false;
113
+ if (words.some((word)=>SENSITIVE_WORDS.has(word))) return true;
114
+ if (SENSITIVE_WORDS.has(words.join(''))) return true;
115
+ for(let i = 0; i < words.length - 1; i++)if (SENSITIVE_WORD_PAIRS.some(([first, second])=>words[i] === first && words[i + 1] === second)) return true;
116
+ return false;
117
+ }
118
+ const BEARER_RE = /\bBearer(?:\s+|\+|%20)[A-Za-z0-9\-._~+/]+=*/gi;
119
+ const JWT_RE = /\beyJ[A-Za-z0-9_-]*\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]*/g;
120
+ const MAX_KV_VALUE_LENGTH = 512;
121
+ const KV_VALUE_REST_RE = /^(?:[^"'&\s,;{}()<>\\%]|%[0-9A-Fa-f]{2})*/;
122
+ const QUOTE = "(?:\\\\?\"|'|%22)?";
123
+ const KV_RE = new RegExp(`(${QUOTE})([A-Za-z][A-Za-z0-9_-]{1,40})(${QUOTE})(\\s*[:=]\\s*|%3A|%3D)(${QUOTE})((?:[^"'&\\s,;{}()<>\\\\%]|%[0-9A-Fa-f]{2}){1,${MAX_KV_VALUE_LENGTH}})`, 'gi');
124
+ const AUTH_SCHEME_RE = /^(?:basic|digest|token|negotiate|ntlm)$/i;
125
+ const MAX_QUOTED_VALUE_TAIL = 2000;
126
+ const AUTH_SCHEME_CREDENTIAL_RE = /^(?:\s+|\+|%20)[^"'&\s,;{}()<>\\]+/;
127
+ function redactKeyValuePairs(text) {
128
+ const re = new RegExp(KV_RE.source, KV_RE.flags);
129
+ let out = '';
130
+ let last = 0;
131
+ let match;
132
+ while(match = re.exec(text)){
133
+ const [whole, q1, key, q2, sep, q3, value] = match;
134
+ const valueStart = match.index + q1.length + key.length + q2.length + sep.length;
135
+ if (isSensitiveKey(key) && !/^\d+$/.test(value) && value !== REDACTED) {
136
+ let end = match.index + whole.length;
137
+ end += KV_VALUE_REST_RE.exec(text.slice(end))?.[0].length ?? 0;
138
+ if (AUTH_SCHEME_RE.test(value)) {
139
+ const credential = AUTH_SCHEME_CREDENTIAL_RE.exec(text.slice(end));
140
+ if (credential) end += credential[0].length;
141
+ }
142
+ if (q3) {
143
+ const close = text.slice(end, end + MAX_QUOTED_VALUE_TAIL + q3.length).indexOf(q3);
144
+ if (close >= 0) end += close;
145
+ }
146
+ out += `${text.slice(last, match.index)}${q1}${key}${q2}${sep}${q3}${REDACTED}`;
147
+ last = end;
148
+ re.lastIndex = end;
149
+ } else re.lastIndex = /[:=]|%3[AD]/i.test(value) ? valueStart : match.index + whole.length;
150
+ }
151
+ return out + text.slice(last);
152
+ }
153
+ function redactString(text) {
154
+ return redactKeyValuePairs(text.replace(BEARER_RE, `Bearer ${REDACTED}`).replace(JWT_RE, REDACTED));
155
+ }
156
+ const REDACT_WINDOW_MARGIN = 1024;
157
+ function redactPrefix(text, max) {
158
+ const window = 4 * max + REDACT_WINDOW_MARGIN;
159
+ if (text.length > window) {
160
+ const redacted = redactString(text.slice(0, window));
161
+ if (redacted.length >= max + REDACT_WINDOW_MARGIN) return redacted;
162
+ }
163
+ return redactString(text);
164
+ }
165
+ function isPlainObject(value) {
166
+ if (null === value || 'object' != typeof value) return false;
167
+ const proto = Object.getPrototypeOf(value);
168
+ return proto === Object.prototype || null === proto;
169
+ }
170
+ function jsonLength(value) {
171
+ try {
172
+ return (JSON.stringify(value) ?? '').length;
173
+ } catch {
174
+ return 1 / 0;
175
+ }
176
+ }
177
+ function truncateString(text, maxLength) {
178
+ if (text.length <= maxLength) return text;
179
+ return `${text.slice(0, maxLength)}…[truncated, ${text.length} chars]`;
180
+ }
181
+ function truncateToJsonLength(text, limit) {
182
+ if (jsonLength(text) <= limit) return text;
183
+ const suffix = `…[truncated, ${text.length} chars]`;
184
+ let keep = Math.min(text.length, limit);
185
+ while(keep > 0){
186
+ const candidate = `${text.slice(0, keep)}${suffix}`;
187
+ const over = jsonLength(candidate) - limit;
188
+ if (over <= 0) return candidate;
189
+ keep -= Math.max(1, Math.ceil(over / 2));
190
+ }
191
+ return suffix.length + 2 <= limit ? suffix : '';
192
+ }
193
+ function describeBinary(value) {
194
+ if ('undefined' != typeof FormData && value instanceof FormData) {
195
+ const keys = Array.from(new Set(Array.from(value.keys())));
196
+ return {
197
+ type: 'FormData',
198
+ keys: keys.slice(0, BASE_LEVEL.maxKeys)
199
+ };
200
+ }
201
+ if ('undefined' != typeof File && value instanceof File) return {
202
+ type: 'File',
203
+ size: value.size
204
+ };
205
+ if ('undefined' != typeof Blob && value instanceof Blob) return {
206
+ type: 'Blob',
207
+ size: value.size
208
+ };
209
+ if (value instanceof ArrayBuffer) return {
210
+ type: 'ArrayBuffer',
211
+ size: value.byteLength
212
+ };
213
+ if (ArrayBuffer.isView(value)) return {
214
+ type: value.constructor?.name || 'ArrayBufferView',
215
+ size: value.byteLength
216
+ };
217
+ return null;
218
+ }
219
+ function isURLSearchParams(value) {
220
+ return 'undefined' != typeof URLSearchParams && value instanceof URLSearchParams;
221
+ }
222
+ function searchParamsToObject(params) {
223
+ const result = {};
224
+ params.forEach((value, key)=>{
225
+ result[key] = value;
226
+ });
227
+ return result;
228
+ }
229
+ function createTrimContext() {
230
+ return {
231
+ seen: new Set(),
232
+ nodes: 0
233
+ };
234
+ }
235
+ const MAX_NESTED_JSON_LENGTH = 1000000;
236
+ function looksLikeJsonContainer(text) {
237
+ const first = text[0];
238
+ const last = text[text.length - 1];
239
+ return '{' === first && '}' === last || '[' === first && ']' === last;
240
+ }
241
+ function looksLikeEncodedJson(text) {
242
+ return text.length >= 2 && '"' === text[0] && '"' === text[text.length - 1] && looksLikeJsonContainer(text.slice(1, -1).trim());
243
+ }
244
+ function parseNestedJson(text) {
245
+ const trimmed = text.trim();
246
+ if (!looksLikeJsonContainer(trimmed) && !looksLikeEncodedJson(trimmed)) return;
247
+ if (trimmed.length > MAX_NESTED_JSON_LENGTH) return `<string: ${text.length} chars, json too large>`;
248
+ try {
249
+ const parsed = JSON.parse(trimmed);
250
+ if (null !== parsed && 'object' == typeof parsed) return parsed;
251
+ if ('string' == typeof parsed) return parsed;
252
+ } catch {}
253
+ }
254
+ const MAX_REDACT_DEPTH = 32;
255
+ function redactKeysDeep(value, depth) {
256
+ if (depth >= MAX_REDACT_DEPTH) return '[Object]';
257
+ if ('string' == typeof value) {
258
+ const nested = parseNestedJson(value);
259
+ if (void 0 === nested || nested === value) return value;
260
+ const redacted = redactKeysDeep(nested, depth + 1);
261
+ return 'string' == typeof redacted ? redacted : JSON.stringify(redacted);
262
+ }
263
+ if (null === value || 'object' != typeof value) return value;
264
+ if (Array.isArray(value)) return value.map((item)=>redactKeysDeep(item, depth + 1));
265
+ const result = {};
266
+ for (const [key, child] of Object.entries(value))result[key] = isSensitiveKey(key) && null !== child && '' !== child ? REDACTED : redactKeysDeep(child, depth + 1);
267
+ return result;
268
+ }
269
+ function trimValue(value, level, depth, parentKey, ctx) {
270
+ if (null === value) return null;
271
+ switch(typeof value){
272
+ case 'string':
273
+ {
274
+ const nested = depth > 0 ? parseNestedJson(value) : void 0;
275
+ if (PRIORITY_KEYS.includes(parentKey ?? '')) {
276
+ const redacted = void 0 === nested ? value : redactKeysDeep(nested, 0);
277
+ const text = 'string' == typeof redacted ? redacted : JSON.stringify(redacted);
278
+ return truncateString(redactPrefix(text, level.maxStringLength), level.maxStringLength);
279
+ }
280
+ if (void 0 !== nested) return trimValue(nested, level, depth, parentKey, ctx);
281
+ return truncateString(redactPrefix(value, level.maxStringLength), level.maxStringLength);
282
+ }
283
+ case 'number':
284
+ case 'boolean':
285
+ return value;
286
+ case 'bigint':
287
+ return value.toString();
288
+ case 'undefined':
289
+ case 'function':
290
+ case 'symbol':
291
+ return;
292
+ default:
293
+ break;
294
+ }
295
+ const obj = value;
296
+ const binary = describeBinary(obj);
297
+ if (binary) return binary;
298
+ if (obj instanceof Date) return Number.isNaN(obj.getTime()) ? null : obj.toISOString();
299
+ if (isURLSearchParams(obj)) return trimValue(searchParamsToObject(obj), level, depth, parentKey, ctx);
300
+ if (obj instanceof Map) return trimValue(Object.fromEntries(obj), level, depth, parentKey, ctx);
301
+ if (obj instanceof Set) return trimValue(Array.from(obj), level, depth, parentKey, ctx);
302
+ if (!Array.isArray(obj) && !isPlainObject(obj) && 'function' == typeof obj.toJSON) try {
303
+ return trimValue(obj.toJSON(), level, depth, parentKey, ctx);
304
+ } catch {
305
+ return '[Unserializable]';
306
+ }
307
+ if (ctx.seen.has(obj)) return '[Circular]';
308
+ if (depth >= level.maxDepth || ctx.nodes >= MAX_TRIM_NODES) return Array.isArray(obj) ? `[Array(${obj.length})]` : '[Object]';
309
+ ctx.nodes++;
310
+ ctx.seen.add(obj);
311
+ try {
312
+ if (Array.isArray(obj)) {
313
+ const items = obj.slice(0, level.maxArrayItems).map((item)=>{
314
+ const trimmed = trimValue(item, level, depth + 1, null, ctx);
315
+ return void 0 === trimmed ? null : trimmed;
316
+ });
317
+ if (obj.length > level.maxArrayItems) items.push(`…[+${obj.length - level.maxArrayItems} items]`);
318
+ return items;
319
+ }
320
+ const record = obj;
321
+ const keys = Object.keys(record);
322
+ const isPriorityScope = 0 === depth || 1 === depth && 'error' === parentKey;
323
+ const priorityKeys = 0 === depth ? TOP_PRIORITY_KEYS : isPriorityScope ? PRIORITY_KEYS : [];
324
+ const kept = keys.filter((key, index)=>index < level.maxKeys || priorityKeys.includes(key));
325
+ const result = {};
326
+ for (const key of kept){
327
+ const child = record[key];
328
+ if (isSensitiveKey(key)) {
329
+ result[key] = null == child || '' === child ? child : REDACTED;
330
+ continue;
331
+ }
332
+ const childLevel = isPriorityScope && PRIORITY_KEYS.includes(key) && 'string' == typeof child ? {
333
+ ...level,
334
+ maxStringLength: BASE_LEVEL.maxStringLength
335
+ } : level;
336
+ const trimmed = trimValue(child, childLevel, depth + 1, key, ctx);
337
+ if (void 0 !== trimmed) result[key] = trimmed;
338
+ }
339
+ if (keys.length > kept.length) result['…'] = `+${keys.length - kept.length} keys`;
340
+ return result;
341
+ } finally{
342
+ ctx.seen.delete(obj);
343
+ }
344
+ }
345
+ function pickPriority(value) {
346
+ const kept = {};
347
+ const rest = {};
348
+ for (const key of Object.keys(value)){
349
+ const child = value[key];
350
+ if (PRIORITY_KEYS.includes(key)) kept[key] = child;
351
+ else if ('error' === key && isPlainObject(child)) {
352
+ const errorKept = {};
353
+ const errorRest = {};
354
+ for (const errorKey of Object.keys(child))if (PRIORITY_KEYS.includes(errorKey)) errorKept[errorKey] = child[errorKey];
355
+ else errorRest[errorKey] = child[errorKey];
356
+ if (Object.keys(errorKept).length > 0) kept.error = errorKept;
357
+ if (Object.keys(errorRest).length > 0) rest.error = errorRest;
358
+ } else if ('error' === key && 'string' == typeof child) kept.error = child;
359
+ else rest[key] = child;
360
+ }
361
+ return Object.keys(kept).length > 0 ? {
362
+ kept,
363
+ rest
364
+ } : null;
365
+ }
366
+ function shrinkKept(kept, limit) {
367
+ let result = kept;
368
+ let budget = BASE_LEVEL.maxStringLength;
369
+ while(jsonLength(result) > limit && budget > 0){
370
+ budget = Math.floor(budget / 2);
371
+ result = mapStrings(kept, (text)=>truncateString(text, budget));
372
+ }
373
+ if (jsonLength(result) > limit) return truncateToJsonLength(JSON.stringify(result), limit);
374
+ return result;
375
+ }
376
+ function mapStrings(value, fn) {
377
+ if ('string' == typeof value) return fn(value);
378
+ if (Array.isArray(value)) return value.map((item)=>mapStrings(item, fn));
379
+ if (!isPlainObject(value)) return value;
380
+ const result = {};
381
+ for (const [key, child] of Object.entries(value))result[key] = mapStrings(child, fn);
382
+ return result;
383
+ }
384
+ function degrade(value, limit) {
385
+ if ('string' == typeof value) return truncateToJsonLength(value, limit);
386
+ const picked = isPlainObject(value) ? pickPriority(value) : null;
387
+ if (!picked) return truncateToJsonLength(JSON.stringify(value) ?? '', limit);
388
+ const kept = shrinkKept(picked.kept, limit);
389
+ if ('string' == typeof kept || 0 === Object.keys(picked.rest).length) return kept;
390
+ const room = limit - jsonLength({
391
+ ...kept,
392
+ _truncated: ''
393
+ });
394
+ if (room < MIN_FIELD_BUDGET) return kept;
395
+ return {
396
+ ...kept,
397
+ _truncated: truncateToJsonLength(JSON.stringify(picked.rest), room)
398
+ };
399
+ }
400
+ function fitToBudget(value, limit) {
401
+ let trimmed;
402
+ for (const level of TRIM_LEVELS){
403
+ trimmed = trimValue(value, level, 0, null, createTrimContext());
404
+ if (void 0 === trimmed) return;
405
+ if (jsonLength(trimmed) <= limit) return trimmed;
406
+ }
407
+ return degrade(trimmed, limit);
408
+ }
409
+ function safeDecode(text) {
410
+ try {
411
+ return decodeURIComponent(text.replace(/\+/g, ' '));
412
+ } catch {
413
+ return text;
414
+ }
415
+ }
416
+ function redactQueryString(query) {
417
+ return query.split('&').map((segment)=>{
418
+ if (!segment) return segment;
419
+ const eq = segment.indexOf('=');
420
+ const rawKey = eq < 0 ? segment : segment.slice(0, eq);
421
+ if (isSensitiveKey(safeDecode(rawKey))) return `${rawKey}=${REDACTED}`;
422
+ if (eq < 0) return segment;
423
+ const decoded = safeDecode(segment.slice(eq + 1));
424
+ const redacted = redactPrefix(decoded, LOG_SANITIZE_LIMITS.url);
425
+ return redacted === decoded ? segment : `${rawKey}=${redacted}`;
426
+ }).join('&');
427
+ }
428
+ function parseQueryString(query) {
429
+ return searchParamsToObject(new URLSearchParams(query));
430
+ }
431
+ function sanitizeUrl(url, basePath) {
432
+ if ('string' != typeof url) return;
433
+ const withoutOrigin = url.replace(/^[a-z][a-z\d+.-]*:\/\/[^/?#]*/i, '').replace(/#.*$/s, '');
434
+ const queryIndex = withoutOrigin.indexOf('?');
435
+ let path = queryIndex < 0 ? withoutOrigin : withoutOrigin.slice(0, queryIndex);
436
+ const query = queryIndex < 0 ? '' : withoutOrigin.slice(queryIndex + 1);
437
+ const base = normalizeBasePath(basePath);
438
+ if (base && (path === base || path.startsWith(`${base}/`))) path = path.slice(base.length) || '/';
439
+ const sanitized = `${redactPrefix(path, LOG_SANITIZE_LIMITS.url)}${query ? `?${redactQueryString(query)}` : ''}`;
440
+ return truncateToJsonLength(sanitized, LOG_SANITIZE_LIMITS.url);
441
+ }
442
+ function sanitizeQueryParams(params, limit = LOG_SANITIZE_LIMITS.params) {
443
+ if (null == params) return;
444
+ const value = 'string' == typeof params ? parseQueryString(params) : params;
445
+ return fitToBudget(value, limit);
446
+ }
447
+ const URLENCODED_RE = /^[^=&\s]+=[^&\s]*(?:&[^=&\s]+=[^&\s]*)*$/;
448
+ function tryParseJson(text) {
449
+ try {
450
+ return {
451
+ value: JSON.parse(text)
452
+ };
453
+ } catch {
454
+ return null;
455
+ }
456
+ }
457
+ function sanitizeRequestBody(data, contentType, limit = LOG_SANITIZE_LIMITS.requestBody) {
458
+ if (null == data) return;
459
+ let value = data;
460
+ if ('string' == typeof data) {
461
+ const parsed = tryParseJson(data);
462
+ if (parsed) value = parsed.value;
463
+ else {
464
+ if (!(/x-www-form-urlencoded/i.test(contentType || '') || URLENCODED_RE.test(data))) return {
465
+ type: 'string',
466
+ length: data.length
467
+ };
468
+ value = parseQueryString(data);
469
+ }
470
+ }
471
+ return fitToBudget(value, limit);
472
+ }
473
+ function sanitizeResponseBody(data, limit = LOG_SANITIZE_LIMITS.responseBody) {
474
+ if (void 0 === data) return;
475
+ let value = data;
476
+ if ('string' == typeof data && /^\s*[[{]/.test(data)) {
477
+ const parsed = tryParseJson(data);
478
+ if (parsed) value = parsed.value;
479
+ }
480
+ return fitToBudget(value, limit);
481
+ }
482
+ function readHeader(headers, name) {
483
+ if (!headers || 'object' != typeof headers) return;
484
+ const lower = name.toLowerCase();
485
+ const record = headers;
486
+ for (const key of Object.keys(record))if (key.toLowerCase() === lower && null != record[key]) return String(record[key]);
487
+ const getter = headers.get;
488
+ if ('function' == typeof getter) try {
489
+ const value = getter.call(headers, name);
490
+ return null == value ? void 0 : String(value);
491
+ } catch {}
492
+ }
493
+ function isAxiosErrorLike(value) {
494
+ if (!value || 'object' != typeof value) return false;
495
+ const candidate = value;
496
+ return true === candidate.isAxiosError && !!candidate.config && 'object' == typeof candidate.config;
497
+ }
498
+ function omitUndefined(value) {
499
+ const result = {};
500
+ for (const key of Object.keys(value))if (void 0 !== value[key]) result[key] = value[key];
501
+ return result;
502
+ }
503
+ const MAX_META_LENGTH = 100;
504
+ function truncateMeta(value) {
505
+ return 'string' == typeof value ? truncateToJsonLength(value, MAX_META_LENGTH) : void 0;
506
+ }
507
+ function shrinkField(holder, key, overflow, resanitize) {
508
+ if (void 0 === holder[key] || overflow <= 0) return;
509
+ const nextLimit = jsonLength(holder[key]) - overflow;
510
+ holder[key] = nextLimit >= MIN_FIELD_BUDGET ? resanitize(nextLimit) : OMITTED;
511
+ }
512
+ function buildAxiosErrorContext(error, basePath) {
513
+ const config = error.config || {};
514
+ const contentType = readHeader(config.headers, 'content-type');
515
+ const request = omitUndefined({
516
+ method: String(config.method || 'get').toUpperCase(),
517
+ url: sanitizeUrl(config.url, basePath),
518
+ params: sanitizeQueryParams(config.params),
519
+ data: sanitizeRequestBody(config.data, contentType)
520
+ });
521
+ const rawResponse = error.response;
522
+ const response = rawResponse ? omitUndefined({
523
+ status: rawResponse.status,
524
+ statusText: truncateMeta(rawResponse.statusText),
525
+ traceId: truncateMeta(readHeader(rawResponse.headers, 'x-log-trace-id')),
526
+ data: sanitizeResponseBody(rawResponse.data)
527
+ }) : void 0;
528
+ const overflow = ()=>jsonLength({
529
+ request,
530
+ response
531
+ }) - LOG_SANITIZE_LIMITS.context;
532
+ const shrinkOrder = [
533
+ [
534
+ response,
535
+ 'data',
536
+ (limit)=>sanitizeResponseBody(rawResponse?.data, limit)
537
+ ],
538
+ [
539
+ request,
540
+ 'data',
541
+ (limit)=>sanitizeRequestBody(config.data, contentType, limit)
542
+ ],
543
+ [
544
+ request,
545
+ 'params',
546
+ (limit)=>sanitizeQueryParams(config.params, limit)
547
+ ]
548
+ ];
549
+ for (const [holder, key, resanitize] of shrinkOrder)if (holder) shrinkField(holder, key, overflow(), resanitize);
550
+ for (const [holder, key] of shrinkOrder){
551
+ if (overflow() <= 0) break;
552
+ if (holder && void 0 !== holder[key]) holder[key] = OMITTED;
553
+ }
554
+ return response ? {
555
+ request,
556
+ response
557
+ } : {
558
+ request
559
+ };
560
+ }
561
+ function serializeAxiosError(error, basePath) {
562
+ const { request, response } = buildAxiosErrorContext(error, basePath);
563
+ return omitUndefined({
564
+ message: error.message,
565
+ request,
566
+ response,
567
+ axiosCode: error.code,
568
+ stack: error.stack
569
+ });
570
+ }
571
+ function serializeNestedAxiosError(error, basePath) {
572
+ const { request, response } = buildAxiosErrorContext(error, basePath);
573
+ return omitUndefined({
574
+ message: error.message,
575
+ name: error.name,
576
+ code: error.code,
577
+ status: error.status ?? error.response?.status,
578
+ request,
579
+ response,
580
+ stack: error.stack
581
+ });
582
+ }
583
+ function shouldExpandAxiosError() {
584
+ return 'production' !== process.env.NODE_ENV;
585
+ }
586
+ function expandTopLevelAxiosError(error) {
587
+ if (!shouldExpandAxiosError() || !isAxiosErrorLike(error)) return;
588
+ try {
589
+ return serializeAxiosError(error, process.env.CLIENT_BASE_PATH);
590
+ } catch {
591
+ return;
592
+ }
593
+ }
594
+ function createNestedAxiosErrorExpander() {
595
+ if (!shouldExpandAxiosError()) return ()=>void 0;
596
+ const basePath = process.env.CLIENT_BASE_PATH;
597
+ const cache = new WeakMap();
598
+ return (raw)=>{
599
+ try {
600
+ if (!isAxiosErrorLike(raw)) return;
601
+ const cached = cache.get(raw);
602
+ if (cached) return cached;
603
+ const expanded = serializeNestedAxiosError(raw, basePath);
604
+ cache.set(raw, expanded);
605
+ return expanded;
606
+ } catch {
607
+ return;
608
+ }
609
+ };
610
+ }
611
+ export { LOG_SANITIZE_LIMITS, REDACTED, buildAxiosErrorContext, createNestedAxiosErrorExpander, expandTopLevelAxiosError, isAxiosErrorLike, isSensitiveKey, readHeader, redactString, sanitizeQueryParams, sanitizeRequestBody, sanitizeResponseBody, sanitizeUrl };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lark-apaas/client-toolkit",
3
- "version": "1.2.82",
3
+ "version": "1.2.83-alpha.20261106064810",
4
4
  "types": "./lib/index.d.ts",
5
5
  "main": "./lib/index.js",
6
6
  "files": [
@@ -102,10 +102,10 @@
102
102
  "@lark-apaas/aily-web-sdk": "^0.0.12",
103
103
  "@lark-apaas/auth-sdk": "^0.1.5",
104
104
  "@lark-apaas/client-capability": "^0.1.7",
105
- "@lark-apaas/dataloom": "^0.1.6",
105
+ "@lark-apaas/dataloom": "^0.1.5",
106
106
  "@lark-apaas/internal-slardar": "^0.0.3",
107
107
  "@lark-apaas/miaoda-inspector": "^1.0.25",
108
- "@lark-apaas/observable-web": "^1.0.11",
108
+ "@lark-apaas/observable-web": "^1.0.6",
109
109
  "@radix-ui/react-avatar": "^1.1.10",
110
110
  "@radix-ui/react-popover": "^1.1.15",
111
111
  "@radix-ui/react-slot": "^1.2.3",
@@ -1,147 +0,0 @@
1
- import { describe, expect, it } from "vitest";
2
- import { runInNewContext } from "node:vm";
3
- import { getWatermarkVariant, readWatermarkCreatedVia } from "../watermark-variant.js";
4
- describe('getWatermarkVariant', ()=>{
5
- it.each([
6
- [
7
- '5',
8
- void 0,
9
- 'doubao'
10
- ],
11
- [
12
- '5',
13
- 'miaoda',
14
- 'doubao'
15
- ],
16
- [
17
- '6',
18
- 'workmate',
19
- 'doubao'
20
- ],
21
- [
22
- '6',
23
- ' WORKMATE ',
24
- 'doubao'
25
- ],
26
- [
27
- '6',
28
- 'workmate_other',
29
- 'miaoda'
30
- ],
31
- [
32
- '6',
33
- 'doubao',
34
- 'doubao'
35
- ],
36
- [
37
- '6',
38
- 'doubao_moa',
39
- 'doubao'
40
- ],
41
- [
42
- '6',
43
- 'doubao_workmate',
44
- 'doubao'
45
- ],
46
- [
47
- '6',
48
- ' DOUBAO_MOA ',
49
- 'doubao'
50
- ],
51
- [
52
- '6',
53
- 'doubaox',
54
- 'miaoda'
55
- ],
56
- [
57
- '6',
58
- 'miaoda',
59
- 'miaoda'
60
- ],
61
- [
62
- '6',
63
- '',
64
- 'miaoda'
65
- ],
66
- [
67
- '6',
68
- void 0,
69
- 'miaoda'
70
- ],
71
- [
72
- void 0,
73
- void 0,
74
- 'miaoda'
75
- ]
76
- ])('source=%s, createdVia=%s => %s', (source, createdVia, expected)=>{
77
- expect(getWatermarkVariant(source, createdVia)).toBe(expected);
78
- });
79
- });
80
- describe('legacy behavior without CreatedVia', ()=>{
81
- it.each([
82
- void 0,
83
- '',
84
- '0',
85
- '1',
86
- '5',
87
- '6',
88
- 'unknown',
89
- 5,
90
- 6
91
- ])('source=%s', (source)=>{
92
- for (const createdVia of [
93
- void 0,
94
- '',
95
- ' '
96
- ])expect(getWatermarkVariant(source, createdVia)).toBe('5' === String(source) ? 'doubao' : 'miaoda');
97
- });
98
- });
99
- describe('readWatermarkCreatedVia with an older preset', ()=>{
100
- it.each([
101
- [
102
- 'browser without process',
103
- {},
104
- void 0
105
- ],
106
- [
107
- 'process shim without env',
108
- {
109
- process: {}
110
- },
111
- void 0
112
- ],
113
- [
114
- 'env without CreatedVia',
115
- {
116
- process: {
117
- env: {}
118
- }
119
- },
120
- void 0
121
- ],
122
- [
123
- 'empty CreatedVia',
124
- {
125
- process: {
126
- env: {
127
- MIAODA_APP_CREATED_VIA: ''
128
- }
129
- }
130
- },
131
- ''
132
- ],
133
- [
134
- 'injected CreatedVia',
135
- {
136
- process: {
137
- env: {
138
- MIAODA_APP_CREATED_VIA: 'doubao_moa'
139
- }
140
- }
141
- },
142
- 'doubao_moa'
143
- ]
144
- ])('%s', (_name, context, expected)=>{
145
- expect(runInNewContext(`(${readWatermarkCreatedVia.toString()})()`, context)).toBe(expected);
146
- });
147
- });
@@ -1,4 +0,0 @@
1
- /** 保留既有 Source 判断,CreatedVia 补充豆包创建来源。 */
2
- export declare function getWatermarkVariant(source: unknown, createdVia: string | undefined): 'doubao' | 'miaoda';
3
- /** 新 SDK 搭配旧 preset 时,新变量可能未被替换,浏览器也可能没有 process。 */
4
- export declare function readWatermarkCreatedVia(): string | undefined;
@@ -1,12 +0,0 @@
1
- function getWatermarkVariant(source, createdVia) {
2
- const origin = (createdVia ?? '').trim().toLowerCase();
3
- return '5' === String(source) || 'workmate' === origin || 'doubao' === origin || origin.startsWith('doubao_') ? 'doubao' : 'miaoda';
4
- }
5
- function readWatermarkCreatedVia() {
6
- try {
7
- return process.env.MIAODA_APP_CREATED_VIA;
8
- } catch {
9
- return;
10
- }
11
- }
12
- export { getWatermarkVariant, readWatermarkCreatedVia };
@@ -1 +0,0 @@
1
- export {};
@@ -1,106 +0,0 @@
1
- import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
2
- import { getAppInfo } from "../getAppInfo.js";
3
- import { isSparkRuntime } from "../../utils/utils.js";
4
- const { getInitialInfoMock } = vi.hoisted(()=>({
5
- getInitialInfoMock: vi.fn()
6
- }));
7
- vi.mock('../../utils/getInitialInfo', ()=>({
8
- getInitialInfo: getInitialInfoMock
9
- }));
10
- vi.mock('../../utils/utils', async (importOriginal)=>{
11
- const actual = await importOriginal();
12
- return {
13
- ...actual,
14
- isSparkRuntime: vi.fn()
15
- };
16
- });
17
- beforeEach(()=>{
18
- getInitialInfoMock.mockReset();
19
- vi.mocked(isSparkRuntime).mockReset();
20
- delete window._appInfo;
21
- });
22
- afterEach(()=>{
23
- delete window._appInfo;
24
- });
25
- describe('getAppInfo', ()=>{
26
- it('returns the cached value on window without fetching', async ()=>{
27
- window._appInfo = {
28
- name: 'cached',
29
- avatar: 'a',
30
- description: 'd'
31
- };
32
- const result = await getAppInfo();
33
- expect(result.name).toBe('cached');
34
- expect(getInitialInfoMock).not.toHaveBeenCalled();
35
- });
36
- it('returns {} when not in spark runtime and no cache', async ()=>{
37
- vi.mocked(isSparkRuntime).mockReturnValue(false);
38
- expect(await getAppInfo()).toEqual({});
39
- expect(getInitialInfoMock).not.toHaveBeenCalled();
40
- });
41
- it('fetches initial info when in spark runtime and writes back to window', async ()=>{
42
- vi.mocked(isSparkRuntime).mockReturnValue(true);
43
- getInitialInfoMock.mockResolvedValue({
44
- app_info: {
45
- app_name: ' My App ',
46
- app_avatar: 'http://a',
47
- app_description: 'd'
48
- }
49
- });
50
- const result = await getAppInfo();
51
- expect(result.name).toBe('My App');
52
- expect(result.avatar).toBe('http://a');
53
- expect(result.description).toBe('d');
54
- expect(window._appInfo).toEqual(result);
55
- });
56
- it('refreshes when refresh=true even with cached value', async ()=>{
57
- window._appInfo = {
58
- name: 'old'
59
- };
60
- vi.mocked(isSparkRuntime).mockReturnValue(true);
61
- getInitialInfoMock.mockResolvedValue({
62
- app_info: {
63
- app_name: 'new',
64
- app_avatar: '',
65
- app_description: ''
66
- }
67
- });
68
- const result = await getAppInfo(true);
69
- expect(result.name).toBe('new');
70
- expect(getInitialInfoMock).toHaveBeenCalledWith(true);
71
- });
72
- it('handles undefined app_info gracefully', async ()=>{
73
- vi.mocked(isSparkRuntime).mockReturnValue(true);
74
- getInitialInfoMock.mockResolvedValue(void 0);
75
- const result = await getAppInfo();
76
- expect(result).toEqual({
77
- name: '',
78
- avatar: '',
79
- description: ''
80
- });
81
- });
82
- it('extracts url when app_avatar is a JSON string', async ()=>{
83
- vi.mocked(isSparkRuntime).mockReturnValue(true);
84
- getInitialInfoMock.mockResolvedValue({
85
- app_info: {
86
- app_name: 'App',
87
- app_avatar: '{"url":"https://a/logo.png"}',
88
- app_description: ''
89
- }
90
- });
91
- const result = await getAppInfo();
92
- expect(result.avatar).toBe('https://a/logo.png');
93
- });
94
- it('returns empty avatar when app_avatar is malformed JSON', async ()=>{
95
- vi.mocked(isSparkRuntime).mockReturnValue(true);
96
- getInitialInfoMock.mockResolvedValue({
97
- app_info: {
98
- app_name: 'App',
99
- app_avatar: '{"url":',
100
- app_description: ''
101
- }
102
- });
103
- const result = await getAppInfo();
104
- expect(result.avatar).toBe('');
105
- });
106
- });