yichong-canva2 1.2.0 → 1.3.0
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 +56 -1
- package/dist/api/reporting.js +64 -0
- package/dist/api/reporting_payload.js +81 -0
- package/dist/login/context.js +3 -0
- package/dist/login/privider.js +11 -2
- package/dist/types/api/index.d.ts +1 -1
- package/dist/types/api/reporting.d.ts +9 -0
- package/dist/types/api/reporting_payload.d.ts +3 -0
- package/dist/types/api/types.d.ts +27 -0
- package/dist/types/login/context.d.ts +2 -2
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -5,11 +5,13 @@
|
|
|
5
5
|
## 使用
|
|
6
6
|
|
|
7
7
|
```sh
|
|
8
|
-
npm install yichong-canva2@1.
|
|
8
|
+
npm install yichong-canva2@1.3.0
|
|
9
9
|
```
|
|
10
10
|
|
|
11
11
|
`1.2.0` 新增文本审核、三个消费接口,以及 Cloudflare R2 单次和分片上传;继续复用原有 Provider。
|
|
12
12
|
|
|
13
|
+
`1.3.0` 新增 `client.reportError`,直接调用现有错误上报 Worker,无需后端改动或额外配置。
|
|
14
|
+
|
|
13
15
|
```tsx
|
|
14
16
|
import { useState } from "react";
|
|
15
17
|
import { YiChongCanvaProvider, useYiChongCanva } from "yichong-canva2";
|
|
@@ -83,6 +85,7 @@ function GenerateButton() {
|
|
|
83
85
|
| `client.createSpecifyPrediction({ owner, name, input })` | `POST /replicate/createSpecifyPrediction` | `{ code: 0, msg: "ok", data: "任务 ID" }` |
|
|
84
86
|
| `client.getPrediction({ id })` | `POST /replicate/getPrediction` | `{ code: 0, msg: "ok", data: { id, status, output, ... } }` |
|
|
85
87
|
| `client.textCheck({ text, scene? })` | `POST /api/public/text-moderation/check` | `{ code: 0, msg: "展示文案", data: { allowed, decision, categories, ... } }` |
|
|
88
|
+
| `client.reportError({ error, source?, stage?, api?, context? })` | `POST https://report.imgkits.com` | Worker 原始 `{ success: true, data: { code: 0, ... } }` 或过滤响应 |
|
|
86
89
|
| `client.reduceFreeCnt({ cnt })` | `POST {baseUrl}/api/user/reduce-free-cnt` | `{ ok: 0, msg: "success" }` |
|
|
87
90
|
| `client.addMonthlyUsage({ cnt })` | `POST {baseUrl}/api/user/add-monthly-usage` | `{ ok: 0, msg: "success" }` |
|
|
88
91
|
| `client.addFreeUsageCnt({ cnt })` | `POST {baseUrl}/api/user/add-free-usage-cnt` | `{ ok: 0, msg: "success" }` |
|
|
@@ -247,6 +250,58 @@ const prediction = await client.getPrediction(
|
|
|
247
250
|
|
|
248
251
|
取消只终止当前 HTTP 等待,不会取消已经创建的后端任务或撤销已提交的消费。创建、查询、文本审核和底层签名的默认请求超时为 60 秒,包含读取响应正文的时间;消费为 30 秒,一键上传为 120 秒。
|
|
249
252
|
|
|
253
|
+
## 错误上报
|
|
254
|
+
|
|
255
|
+
继续使用同一个 Provider,业务代码直接调用 `client.reportError`。`error` 接受 Error、ApiError、字符串或其他被抛出的值。Provider 自动补充产品渠道、应用 ID、应用版本及可用的用户 ID。工具包内置现有 Worker 地址和固定上报令牌,机器人固定为 `ROBOT_MONITOR`,应用无需新增配置或修改后端。
|
|
256
|
+
|
|
257
|
+
固定令牌会随 npm 包和应用浏览器产物公开,不能视为保密凭据。此请求不向 Worker 发送用户 JWT 或 passport;这类值会从诊断正文中移除。上报可在 Provider 登录前调用,尚未获得的用户 ID 标为 unknown。
|
|
258
|
+
|
|
259
|
+
```tsx
|
|
260
|
+
function GenerateButton() {
|
|
261
|
+
const client = useYiChongCanva();
|
|
262
|
+
const [message, setMessage] = useState("");
|
|
263
|
+
const [busy, setBusy] = useState(false);
|
|
264
|
+
|
|
265
|
+
async function generate() {
|
|
266
|
+
if (busy || client.loginStatus !== "success") return;
|
|
267
|
+
setBusy(true);
|
|
268
|
+
setMessage("");
|
|
269
|
+
try {
|
|
270
|
+
const created = await client.createSpecifyPrediction({
|
|
271
|
+
owner: "your-model-owner",
|
|
272
|
+
name: "your-model-name",
|
|
273
|
+
input: { prompt: "一只猫" },
|
|
274
|
+
});
|
|
275
|
+
setMessage(`已创建任务:${created.data}`);
|
|
276
|
+
} catch (error) {
|
|
277
|
+
setMessage(error instanceof Error ? error.message : "生成失败");
|
|
278
|
+
// 单独处理上报失败;界面仍显示原本的业务错误。
|
|
279
|
+
void client.reportError({
|
|
280
|
+
error,
|
|
281
|
+
source: "api",
|
|
282
|
+
stage: "create_prediction",
|
|
283
|
+
context: { model: "your-model-name" },
|
|
284
|
+
}).catch(() => {});
|
|
285
|
+
} finally {
|
|
286
|
+
setBusy(false);
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
return <>
|
|
291
|
+
<button disabled={busy || client.loginStatus !== "success"} onClick={() => void generate()}>
|
|
292
|
+
生成
|
|
293
|
+
</button>
|
|
294
|
+
{message && <p role="status">{message}</p>}
|
|
295
|
+
</>;
|
|
296
|
+
}
|
|
297
|
+
```
|
|
298
|
+
|
|
299
|
+
`source` 默认 `"ui"`,支持 `ui/api/runtime/promise/react/upload/host_sdk`;`stage` 是可选的业务阶段(最多 128 字符)。`api` 可填 `{ method, url, status, request_id, response_code }`,`context` 是小型诊断对象。ApiError 自动提取 code、status、data.request_id,不发送完整 data。message 最多 2000 字符,stack 最多 3000;context 截断长字符串、数量和深度,移除常见凭据及 base64 文件。整体内容过大时抛出 `invalid_request`。应用仍应只传诊断所需信息,例如模型名、任务 ID 和处理阶段,避免传原始用户输入或文件。
|
|
300
|
+
|
|
301
|
+
成功原样返回 Worker 的 `{ success: true, data, ... }`。`data.status="ignored"` 表示旧 Worker 过滤了噪声,可能附带 reason/country;其他成功结果已经确认飞书业务码为 0。HTTP 成功但飞书业务码非 0 仍抛出 ApiError;上报的错误码为 reporting_failed、invalid_response、network_error、timeout 或 aborted 等,保留 HTTP 状态及可读取的 Retry-After,不回显上游内部错误正文。没有自动捕获全局错误、React 错误或 API 失败,由业务显式调用。
|
|
302
|
+
|
|
303
|
+
默认超时 10 秒,支持第二参数 `{ signal, timeoutMs }`,只请求一次。沿用 Worker 的噪声过滤规则,本次不新增服务端限流或网关转发。上报失败不要再次上报自身异常;缺少 Provider 时抛出 provider_missing。`apiBaseUrl` 不影响上报地址,调用方不能覆盖机器人、地址或令牌。
|
|
304
|
+
|
|
250
305
|
## 开发
|
|
251
306
|
|
|
252
307
|
```bash
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import { ApiError } from "./error.js";
|
|
2
|
+
import { isNonemptyString, invalid, readJson, isObject, backendError } from "./request.js";
|
|
3
|
+
import { reportingPayload } from "./reporting_payload.js";
|
|
4
|
+
import { withRequest } from "./transport.js";
|
|
5
|
+
const reportUrl = "https://report.imgkits.com";
|
|
6
|
+
const reportToken = "base64:MsUJo+qAhIVGPx52r1mbxCYn5YbWtCx8FQ7pTaHEvRo=";
|
|
7
|
+
function createErrorReportingApi(getContext) {
|
|
8
|
+
return {
|
|
9
|
+
async reportError(params, options) {
|
|
10
|
+
var _a, _b, _c;
|
|
11
|
+
const context = getContext();
|
|
12
|
+
if (!isNonemptyString(context.productName) || context.productName.length > 64 || !isNonemptyString(context.appId) || context.appId.length > 64 || !Number.isFinite(context.version) || String(context.version).length > 64) {
|
|
13
|
+
invalid("Error reporting requires the Provider productName, appId and version.");
|
|
14
|
+
}
|
|
15
|
+
const secrets = [reportToken, context.userStatus.jwt, (_a = context.userStatus.profile) == null ? void 0 : _a.token, (_b = context.userStatus.drive) == null ? void 0 : _b.fresh_token, context.passport].filter((value) => typeof value === "string" && value.length > 0);
|
|
16
|
+
const details = {
|
|
17
|
+
time: (/* @__PURE__ */ new Date()).toISOString(),
|
|
18
|
+
app_channel: context.productName,
|
|
19
|
+
platform: "canva_addon",
|
|
20
|
+
app_id: context.appId,
|
|
21
|
+
app_version: String(context.version),
|
|
22
|
+
user_id: ((_c = context.userStatus.profile) == null ? void 0 : _c.id) ?? "unknown",
|
|
23
|
+
platform_uid: context.userStatus.userId ?? "unknown",
|
|
24
|
+
...reportingPayload(params, secrets)
|
|
25
|
+
};
|
|
26
|
+
let message = Object.entries(details).map(([key, value]) => `${key}: ${typeof value === "string" ? value : JSON.stringify(value)}`).join("\n");
|
|
27
|
+
for (const secret of secrets) {
|
|
28
|
+
if (secret.length >= 4) message = message.split(secret).join("[redacted]");
|
|
29
|
+
}
|
|
30
|
+
message = message.replace(/</g, "<").replace(/>/g, ">");
|
|
31
|
+
const body = JSON.stringify({ robot: "ROBOT_MONITOR", title: "Canva 应用错误", titleColor: "red", message });
|
|
32
|
+
if (new TextEncoder().encode(body).length > 16384) invalid("Error report is too large; provide a smaller context.");
|
|
33
|
+
return withRequest({ ...options, timeoutMs: (options == null ? void 0 : options.timeoutMs) ?? 1e4 }, async (signal) => {
|
|
34
|
+
const response = await fetch(reportUrl, {
|
|
35
|
+
method: "POST",
|
|
36
|
+
headers: { "Content-Type": "application/json", Authorization: `Bearer ${reportToken}` },
|
|
37
|
+
body,
|
|
38
|
+
signal,
|
|
39
|
+
credentials: "omit",
|
|
40
|
+
redirect: "error"
|
|
41
|
+
});
|
|
42
|
+
const result = await readJson(response);
|
|
43
|
+
if (!response.ok || isObject(result) && result.success === false) {
|
|
44
|
+
throw backendError(response, { code: "reporting_failed", msg: "Error reporting failed." }, "reporting_failed");
|
|
45
|
+
}
|
|
46
|
+
if (!isObject(result) || result.success !== true || !isObject(result.data)) {
|
|
47
|
+
throw new ApiError("Worker returned invalid error report confirmation.", "invalid_response", response.status);
|
|
48
|
+
}
|
|
49
|
+
if (result.data.status === "ignored") {
|
|
50
|
+
if (result.data.reason !== void 0 && typeof result.data.reason !== "string") {
|
|
51
|
+
throw new ApiError("Worker returned invalid error report confirmation.", "invalid_response", response.status);
|
|
52
|
+
}
|
|
53
|
+
} else {
|
|
54
|
+
const feishuCode = Object.prototype.hasOwnProperty.call(result.data, "code") ? result.data.code : result.data.StatusCode;
|
|
55
|
+
if (feishuCode !== 0) throw new ApiError("Feishu did not confirm the error report.", "reporting_failed", response.status);
|
|
56
|
+
}
|
|
57
|
+
return result;
|
|
58
|
+
});
|
|
59
|
+
}
|
|
60
|
+
};
|
|
61
|
+
}
|
|
62
|
+
export {
|
|
63
|
+
createErrorReportingApi
|
|
64
|
+
};
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
import { isObject, invalid, isNonemptyString } from "./request.js";
|
|
2
|
+
const sources = ["ui", "api", "runtime", "promise", "react", "upload", "host_sdk"];
|
|
3
|
+
const sensitiveKey = /authorization|token|jwt|passport|password|secret|cookie|credential|signature|access[-_]?key|access[-_]?ticket|email/i;
|
|
4
|
+
function reportingPayload(params, secrets = []) {
|
|
5
|
+
var _a, _b, _c;
|
|
6
|
+
if (!isObject(params) || !Object.prototype.hasOwnProperty.call(params, "error") || Object.keys(params).some((key) => !["error", "source", "stage", "api", "context"].includes(key))) {
|
|
7
|
+
invalid("reportError requires an error and supports source, stage, api and context only.");
|
|
8
|
+
}
|
|
9
|
+
if (params.source !== void 0 && !sources.includes(params.source)) invalid("Invalid error report source.");
|
|
10
|
+
if (params.stage !== void 0 && (!isNonemptyString(params.stage) || params.stage.length > 128)) invalid("stage must contain 1–128 characters.");
|
|
11
|
+
if (params.context !== void 0 && !isObject(params.context)) invalid("context must be an object.");
|
|
12
|
+
if (params.api !== void 0 && (!isObject(params.api) || Object.keys(params.api).some((key) => !["method", "url", "status", "request_id", "response_code"].includes(key)))) {
|
|
13
|
+
invalid("Invalid error report API details.");
|
|
14
|
+
}
|
|
15
|
+
for (const key of ["method", "url", "request_id"]) {
|
|
16
|
+
if (((_a = params.api) == null ? void 0 : _a[key]) !== void 0 && typeof params.api[key] !== "string") invalid(`api.${key} must be a string.`);
|
|
17
|
+
}
|
|
18
|
+
if (((_b = params.api) == null ? void 0 : _b.status) !== void 0 && (!Number.isInteger(params.api.status) || params.api.status < 0 || params.api.status > 599)) {
|
|
19
|
+
invalid("api.status must be an HTTP status number.");
|
|
20
|
+
}
|
|
21
|
+
if (((_c = params.api) == null ? void 0 : _c.response_code) !== void 0 && typeof params.api.response_code !== "string" && !(typeof params.api.response_code === "number" && Number.isFinite(params.api.response_code))) {
|
|
22
|
+
invalid("api.response_code must be a string or finite number.");
|
|
23
|
+
}
|
|
24
|
+
const safeString = (value, limit = 1e3) => {
|
|
25
|
+
let text = value;
|
|
26
|
+
for (const secret of secrets) {
|
|
27
|
+
if (secret.length >= 4) text = text.split(secret).join("[redacted]");
|
|
28
|
+
}
|
|
29
|
+
text = text.replace(/Bearer\s+[^\s,;"'<>]+/gi, "Bearer [redacted]").replace(/(https?:\/\/)[^\s/@]+:[^\s/@]+@/gi, "$1[redacted]@").replace(/([?&](?:X-Amz-[^=&#\s]*|AWSAccessKeyId|Signature|access_token|token|jwt|passport|secret|password)=)[^&#\s]*/gi, "$1[redacted]").replace(/((?:authorization|access[-_]?ticket|token|jwt|passport|secret|password)\s*[:=]\s*)[^\s,;"'<>&#]+/gi, "$1[redacted]").replace(/data:[^,\s]+;base64,[a-z0-9+/=]+/gi, "[binary omitted]");
|
|
30
|
+
text = new TextDecoder().decode(new TextEncoder().encode(text));
|
|
31
|
+
return Array.from(text).slice(0, limit).join("");
|
|
32
|
+
};
|
|
33
|
+
const ancestors = /* @__PURE__ */ new Set();
|
|
34
|
+
const safeValue = (value, depth = 0) => {
|
|
35
|
+
if (value === null || typeof value === "boolean") return value;
|
|
36
|
+
if (typeof value === "number") return Number.isFinite(value) ? value : "[non-finite number]";
|
|
37
|
+
if (typeof value === "string") return safeString(value, 500);
|
|
38
|
+
if (typeof value !== "object") return "[unsupported value]";
|
|
39
|
+
if (ancestors.has(value)) return "[circular]";
|
|
40
|
+
if (depth >= 3) return "[truncated]";
|
|
41
|
+
if (!Array.isArray(value) && Object.getPrototypeOf(value) !== Object.prototype && Object.getPrototypeOf(value) !== null) {
|
|
42
|
+
return "[non-JSON object omitted]";
|
|
43
|
+
}
|
|
44
|
+
ancestors.add(value);
|
|
45
|
+
try {
|
|
46
|
+
if (Array.isArray(value)) return value.slice(0, 10).map((item) => safeValue(item, depth + 1));
|
|
47
|
+
return Object.fromEntries(Object.entries(value).slice(0, 20).map(([key, item]) => [
|
|
48
|
+
safeString(key, 128),
|
|
49
|
+
sensitiveKey.test(key) ? "[redacted]" : safeValue(item, depth + 1)
|
|
50
|
+
]));
|
|
51
|
+
} finally {
|
|
52
|
+
ancestors.delete(value);
|
|
53
|
+
}
|
|
54
|
+
};
|
|
55
|
+
const original = params.error;
|
|
56
|
+
const fields = isObject(original) ? original : void 0;
|
|
57
|
+
const error = {
|
|
58
|
+
name: safeString(isNonemptyString(fields == null ? void 0 : fields.name) ? fields.name : "Error", 128),
|
|
59
|
+
message: safeString(typeof original === "string" ? original : typeof (fields == null ? void 0 : fields.message) === "string" ? fields.message : JSON.stringify(safeValue(original)), 2e3)
|
|
60
|
+
};
|
|
61
|
+
if (typeof (fields == null ? void 0 : fields.stack) === "string") error.stack = safeString(fields.stack, 3e3);
|
|
62
|
+
if (typeof (fields == null ? void 0 : fields.code) === "string" || typeof (fields == null ? void 0 : fields.code) === "number" && Number.isFinite(fields.code)) {
|
|
63
|
+
error.code = typeof fields.code === "string" ? safeString(fields.code, 128) : fields.code;
|
|
64
|
+
}
|
|
65
|
+
if (Number.isInteger(fields == null ? void 0 : fields.status) && (fields == null ? void 0 : fields.status) >= 0 && (fields == null ? void 0 : fields.status) <= 599) error.status = fields == null ? void 0 : fields.status;
|
|
66
|
+
if (isObject(fields == null ? void 0 : fields.data) && typeof fields.data.request_id === "string") error.request_id = safeString(fields.data.request_id, 128);
|
|
67
|
+
const payload = { error, source: params.source ?? "ui" };
|
|
68
|
+
if (params.stage !== void 0) payload.stage = safeString(params.stage, 128);
|
|
69
|
+
if (params.context !== void 0) payload.context = safeValue(params.context);
|
|
70
|
+
if (params.api !== void 0) {
|
|
71
|
+
payload.api = safeValue(params.api);
|
|
72
|
+
if (isObject(payload.api) && typeof payload.api.response_code === "string") {
|
|
73
|
+
payload.api.response_code = safeString(payload.api.response_code, 128);
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
if (new TextEncoder().encode(JSON.stringify(payload)).length > 16e3) invalid("Error report is too large; provide a smaller context.");
|
|
77
|
+
return payload;
|
|
78
|
+
}
|
|
79
|
+
export {
|
|
80
|
+
reportingPayload
|
|
81
|
+
};
|
package/dist/login/context.js
CHANGED
|
@@ -39,6 +39,9 @@ const YiChongCanvaContext = React.createContext(
|
|
|
39
39
|
textCheck: async () => {
|
|
40
40
|
throw new ApiError("Wrap your components in YiChongCanvaProvider first.", "provider_missing");
|
|
41
41
|
},
|
|
42
|
+
reportError: async () => {
|
|
43
|
+
throw new ApiError("Wrap your components in YiChongCanvaProvider first.", "provider_missing");
|
|
44
|
+
},
|
|
42
45
|
reduceFreeCnt: async () => {
|
|
43
46
|
throw new ApiError("Wrap your components in YiChongCanvaProvider first.", "provider_missing");
|
|
44
47
|
},
|
package/dist/login/privider.js
CHANGED
|
@@ -8,6 +8,7 @@ import { createPredictionApi } from "../api/predictions.js";
|
|
|
8
8
|
import { createTextModerationApi } from "../api/moderation.js";
|
|
9
9
|
import { createUsageApi } from "../api/usage.js";
|
|
10
10
|
import { createUploadApi } from "../api/uploads.js";
|
|
11
|
+
import { createErrorReportingApi } from "../api/reporting.js";
|
|
11
12
|
function reduceFreeTimes(baseUrl, passport, cnt = 1) {
|
|
12
13
|
const header = {
|
|
13
14
|
"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
|
|
@@ -66,8 +67,8 @@ const YiChongCanvaProvider = ({
|
|
|
66
67
|
const sessionStopRef = useRef(null);
|
|
67
68
|
const [loginStatus, setLoginStatus] = useState("idle");
|
|
68
69
|
const userStatusRef = useRef({});
|
|
69
|
-
const apiConfigRef = useRef({ apiBaseUrl, baseUrl, uploadBaseUrl, productName, getLocale });
|
|
70
|
-
apiConfigRef.current = { apiBaseUrl, baseUrl, uploadBaseUrl, productName, getLocale };
|
|
70
|
+
const apiConfigRef = useRef({ apiBaseUrl, baseUrl, uploadBaseUrl, productName, appId, version, getLocale });
|
|
71
|
+
apiConfigRef.current = { apiBaseUrl, baseUrl, uploadBaseUrl, productName, appId, version, getLocale };
|
|
71
72
|
const passportRef = useRef(null);
|
|
72
73
|
const onPassport = (passport, userId, uid) => {
|
|
73
74
|
passportRef.current = { passport, userId, uid, productName };
|
|
@@ -86,6 +87,13 @@ const YiChongCanvaProvider = ({
|
|
|
86
87
|
return { ...context, passport: matches ? credential == null ? void 0 : credential.passport : void 0 };
|
|
87
88
|
}));
|
|
88
89
|
const [uploadApi] = useState(() => createUploadApi(getApiContext));
|
|
90
|
+
const [errorReportingApi] = useState(() => createErrorReportingApi(() => {
|
|
91
|
+
var _a;
|
|
92
|
+
return {
|
|
93
|
+
...getApiContext(),
|
|
94
|
+
passport: (_a = passportRef.current) == null ? void 0 : _a.passport
|
|
95
|
+
};
|
|
96
|
+
}));
|
|
89
97
|
useEffect(() => {
|
|
90
98
|
userStatusRef.current = userStatus;
|
|
91
99
|
}, [userStatus]);
|
|
@@ -589,6 +597,7 @@ const YiChongCanvaProvider = ({
|
|
|
589
597
|
...textModerationApi,
|
|
590
598
|
...usageApi,
|
|
591
599
|
...uploadApi,
|
|
600
|
+
...errorReportingApi,
|
|
592
601
|
userStatus,
|
|
593
602
|
updateUserStatus,
|
|
594
603
|
handleLogin: login,
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
export { ApiError } from './error';
|
|
2
|
-
export type { ApiRequestOptions, ApiResponse, CompleteUploadParams, CompleteUploadResponse, TextCheckParams, CreateSpecifyPredictionParams, GetPredictionParams, GeneratePresignedUrlParams, GetUploadUrlParams, InitiateUploadParams, InitiateUploadResponse, JsonObject, JsonValue, Prediction, PredictionApi, PresignedUrlResponse, TextModerationApi, TextModerationCategory, TextModerationDecision, TextModerationResult, UploadApi, UploadFileParams, UploadFileResult, UploadedPart, UploadPartUrlResponse, UsageApi, UsageParams, UsageResponse, } from './types';
|
|
2
|
+
export type { ApiRequestOptions, ApiResponse, CompleteUploadParams, CompleteUploadResponse, TextCheckParams, CreateSpecifyPredictionParams, ErrorReportingApi, ErrorReportSource, GetPredictionParams, GeneratePresignedUrlParams, GetUploadUrlParams, InitiateUploadParams, InitiateUploadResponse, JsonObject, JsonValue, Prediction, PredictionApi, ReportErrorParams, ReportErrorResult, PresignedUrlResponse, TextModerationApi, TextModerationCategory, TextModerationDecision, TextModerationResult, UploadApi, UploadFileParams, UploadFileResult, UploadedPart, UploadPartUrlResponse, UsageApi, UsageParams, UsageResponse, } from './types';
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { ApiContext } from './request';
|
|
2
|
+
import { ErrorReportingApi } from './types';
|
|
3
|
+
export interface ReportingContext extends Pick<ApiContext, "userStatus" | "productName"> {
|
|
4
|
+
appId: string;
|
|
5
|
+
version: number;
|
|
6
|
+
/** 只用于从诊断内容中移除当前账户凭据。 */
|
|
7
|
+
passport?: string;
|
|
8
|
+
}
|
|
9
|
+
export declare function createErrorReportingApi(getContext: () => ReportingContext): ErrorReportingApi;
|
|
@@ -69,6 +69,33 @@ export interface TextModerationApi {
|
|
|
69
69
|
/** 调用公共文本审核入口;内容拒绝仍返回 code=0。 */
|
|
70
70
|
textCheck(params: TextCheckParams, options?: ApiRequestOptions): Promise<ApiResponse<TextModerationResult>>;
|
|
71
71
|
}
|
|
72
|
+
export type ErrorReportSource = "ui" | "api" | "runtime" | "promise" | "react" | "upload" | "host_sdk";
|
|
73
|
+
export interface ReportErrorParams {
|
|
74
|
+
/** Error、ApiError、字符串或其他错误值;工具包只提取诊断字段,脱敏并限制长度。 */
|
|
75
|
+
error: unknown;
|
|
76
|
+
source?: ErrorReportSource;
|
|
77
|
+
/** 业务阶段,例如 create_prediction / poll_prediction / add_to_design。 */
|
|
78
|
+
stage?: string;
|
|
79
|
+
api?: {
|
|
80
|
+
method?: string;
|
|
81
|
+
url?: string;
|
|
82
|
+
status?: number;
|
|
83
|
+
request_id?: string;
|
|
84
|
+
response_code?: string | number;
|
|
85
|
+
};
|
|
86
|
+
/** 少量诊断信息,例如任务 ID、模型名、成功张数;不要传完整请求或响应。 */
|
|
87
|
+
context?: Record<string, unknown>;
|
|
88
|
+
}
|
|
89
|
+
export interface ReportErrorResult {
|
|
90
|
+
/** 原样返回 Worker 的成功响应;data.status=ignored 表示过滤,其他成功响应已验证飞书业务码为 0。 */
|
|
91
|
+
success: true;
|
|
92
|
+
data: Record<string, unknown>;
|
|
93
|
+
[key: string]: unknown;
|
|
94
|
+
}
|
|
95
|
+
export interface ErrorReportingApi {
|
|
96
|
+
/** 单次上报,不自动捕获错误或重试。失败会抛出 ApiError,调用方应独立捕获。 */
|
|
97
|
+
reportError(params: ReportErrorParams, options?: ApiRequestOptions): Promise<ReportErrorResult>;
|
|
98
|
+
}
|
|
72
99
|
export interface UsageParams {
|
|
73
100
|
/** 消费数量;reduceFreeCnt / addMonthlyUsage 最多两位小数,addFreeUsageCnt 最多一位。 */
|
|
74
101
|
cnt: number;
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { default as React } from 'react';
|
|
2
|
-
import { PredictionApi, TextModerationApi, UploadApi, UsageApi } from '../api/types';
|
|
2
|
+
import { ErrorReportingApi, PredictionApi, TextModerationApi, UploadApi, UsageApi } from '../api/types';
|
|
3
3
|
import { canUseError, CheckoutSessionOptions, TestMode, UserStatus } from './interface';
|
|
4
4
|
/**
|
|
5
5
|
*
|
|
@@ -17,7 +17,7 @@ import { canUseError, CheckoutSessionOptions, TestMode, UserStatus } from './int
|
|
|
17
17
|
* @property {() => string} getPricingLink 获取付费链接
|
|
18
18
|
* @property {() => void} updateTestMode 更新测试模式, 只有在开发环境下有效
|
|
19
19
|
*/
|
|
20
|
-
export interface YiChongCanvaContextType extends PredictionApi, TextModerationApi, UsageApi, UploadApi {
|
|
20
|
+
export interface YiChongCanvaContextType extends PredictionApi, TextModerationApi, UsageApi, UploadApi, ErrorReportingApi {
|
|
21
21
|
userStatus: UserStatus;
|
|
22
22
|
updateUserStatus: (user: Partial<UserStatus>) => void;
|
|
23
23
|
handleLogin: () => void;
|