yichong-canva2 1.1.28 → 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 +224 -6
- package/dist/api/error.js +3 -1
- package/dist/api/moderation.js +32 -0
- package/dist/api/reporting.js +64 -0
- package/dist/api/reporting_payload.js +81 -0
- package/dist/api/request.js +73 -80
- package/dist/api/transport.js +42 -0
- package/dist/api/uploads.js +218 -0
- package/dist/api/usage.js +57 -0
- package/dist/login/context.js +30 -0
- package/dist/login/login/login.js +7 -3
- package/dist/login/privider.js +38 -5
- package/dist/types/api/error.d.ts +8 -1
- package/dist/types/api/index.d.ts +1 -1
- package/dist/types/api/moderation.d.ts +4 -0
- package/dist/types/api/reporting.d.ts +9 -0
- package/dist/types/api/reporting_payload.d.ts +3 -0
- package/dist/types/api/request.d.ts +13 -1
- package/dist/types/api/transport.d.ts +4 -0
- package/dist/types/api/types.d.ts +144 -0
- package/dist/types/api/uploads.d.ts +6 -0
- package/dist/types/api/usage.d.ts +9 -0
- package/dist/types/login/context.d.ts +2 -2
- package/dist/types/login/login/login.d.ts +4 -2
- package/dist/types/login/privider.d.ts +3 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -1,9 +1,17 @@
|
|
|
1
1
|
# yichong-canva2
|
|
2
2
|
|
|
3
|
-
使用一个 `YiChongCanvaProvider` 管理登录、订阅和额度,通过 `useYiChongCanva()`
|
|
3
|
+
使用一个 `YiChongCanvaProvider` 管理登录、订阅和额度,通过 `useYiChongCanva()` 直接调用后端接口。
|
|
4
4
|
|
|
5
5
|
## 使用
|
|
6
6
|
|
|
7
|
+
```sh
|
|
8
|
+
npm install yichong-canva2@1.3.0
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
`1.2.0` 新增文本审核、三个消费接口,以及 Cloudflare R2 单次和分片上传;继续复用原有 Provider。
|
|
12
|
+
|
|
13
|
+
`1.3.0` 新增 `client.reportError`,直接调用现有错误上报 Worker,无需后端改动或额外配置。
|
|
14
|
+
|
|
7
15
|
```tsx
|
|
8
16
|
import { useState } from "react";
|
|
9
17
|
import { YiChongCanvaProvider, useYiChongCanva } from "yichong-canva2";
|
|
@@ -26,15 +34,21 @@ function GenerateButton() {
|
|
|
26
34
|
const [error, setError] = useState("");
|
|
27
35
|
const [status, setStatus] = useState("");
|
|
28
36
|
const [busy, setBusy] = useState(false);
|
|
37
|
+
const [prompt, setPrompt] = useState("a cat");
|
|
29
38
|
|
|
30
39
|
async function generate() {
|
|
31
40
|
setError("");
|
|
32
41
|
setBusy(true);
|
|
33
42
|
try {
|
|
43
|
+
const moderation = await client.textCheck({ text: prompt });
|
|
44
|
+
if (moderation.data.allowed !== true) {
|
|
45
|
+
setError(moderation.msg);
|
|
46
|
+
return;
|
|
47
|
+
}
|
|
34
48
|
const created = await client.createSpecifyPrediction({
|
|
35
49
|
owner: "openai",
|
|
36
50
|
name: "gpt-image-2",
|
|
37
|
-
input: { prompt
|
|
51
|
+
input: { prompt },
|
|
38
52
|
});
|
|
39
53
|
const prediction = await client.getPrediction({ id: created.data });
|
|
40
54
|
setStatus(prediction.data.status);
|
|
@@ -50,6 +64,7 @@ function GenerateButton() {
|
|
|
50
64
|
}
|
|
51
65
|
|
|
52
66
|
return <>
|
|
67
|
+
<textarea value={prompt} disabled={busy} onChange={event => setPrompt(event.target.value)} />
|
|
53
68
|
<button disabled={client.loginStatus !== "success" || busy} onClick={() => void generate()}>Generate</button>
|
|
54
69
|
{status && <p>{status}</p>}
|
|
55
70
|
{error && <p role="alert">{error}</p>}
|
|
@@ -59,6 +74,8 @@ function GenerateButton() {
|
|
|
59
74
|
|
|
60
75
|
`baseUrl` 沿用原有账户扣费接口的地址。AI 请求默认使用 `https://api.imgkits.com`,可以通过可选的 `apiBaseUrl` 指定测试地址。
|
|
61
76
|
|
|
77
|
+
文件签名服务默认使用 `https://ai.imgkits.com`,可通过 Provider 的 `uploadBaseUrl` 指定测试服务;上传后的公开域名由签名响应的 `endpointBaseUrl` 决定。
|
|
78
|
+
|
|
62
79
|
语言默认在每次请求时读取 `document.documentElement.lang` 或浏览器语言;应用有自己的国际化状态时,在 Provider 上传 `getLocale={() => currentLocale}`。
|
|
63
80
|
|
|
64
81
|
## 后端接口
|
|
@@ -67,13 +84,162 @@ function GenerateButton() {
|
|
|
67
84
|
| --- | --- | --- |
|
|
68
85
|
| `client.createSpecifyPrediction({ owner, name, input })` | `POST /replicate/createSpecifyPrediction` | `{ code: 0, msg: "ok", data: "任务 ID" }` |
|
|
69
86
|
| `client.getPrediction({ id })` | `POST /replicate/getPrediction` | `{ code: 0, msg: "ok", data: { id, status, output, ... } }` |
|
|
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, ... } }` 或过滤响应 |
|
|
89
|
+
| `client.reduceFreeCnt({ cnt })` | `POST {baseUrl}/api/user/reduce-free-cnt` | `{ ok: 0, msg: "success" }` |
|
|
90
|
+
| `client.addMonthlyUsage({ cnt })` | `POST {baseUrl}/api/user/add-monthly-usage` | `{ ok: 0, msg: "success" }` |
|
|
91
|
+
| `client.addFreeUsageCnt({ cnt })` | `POST {baseUrl}/api/user/add-free-usage-cnt` | `{ ok: 0, msg: "success" }` |
|
|
92
|
+
| `client.generatePresignedUrl({ objectName, bucketName? })` | `POST {uploadBaseUrl}/api/generate-presigned-url` | `{ success: true, url, endpointBaseUrl?, ... }` |
|
|
93
|
+
| `client.initiateUpload({ objectName, bucketName?, contentType? })` | `POST {uploadBaseUrl}/upload/initiate-upload` | `{ UploadId, Bucket?, Key?, ... }` |
|
|
94
|
+
| `client.getUploadUrl({ objectName, uploadId, partNumber, bucketName? })` | `POST {uploadBaseUrl}/upload/get-upload-url` | `{ url, ... }` |
|
|
95
|
+
| `client.completeUpload({ objectName, uploadId, parts, bucketName? })` | `POST {uploadBaseUrl}/upload/complete-upload` | `{ ETag, Bucket?, Key?, Location?, ... }` |
|
|
96
|
+
| `client.uploadFile({ file, ... })` | 自动单次 PUT 或初始化 → 分片签名 / PUT → 合并 | `{ url: "公开资源地址", key, endpointBaseUrl }` |
|
|
97
|
+
|
|
98
|
+
Provider 自动注入自有后端请求 query 中的 `uid`、`platform_uid`、`platform=canva_addon`、`app_channel`,以及 `Accept-Language`。AI 接口还携带 `Authorization: Bearer <jwt>`、`Channel: ai`;消费接口使用 `X-Access-Ticket`、`X-Access-Channel`;签名接口使用 `Channel: node-nauth`。R2 PUT 原样使用签名 URL,只携带文件的 `Content-Type`。创建请求中的 `user_id` 使用系统用户 ID(`userStatus.profile.id`)。公共审核只要求有效的业务 JWT;`uid` 和 `platform_uid` 在账户状态包含这些值时才附带,审核身份由后端验签确定。调用方无需维护这些字段。
|
|
99
|
+
|
|
100
|
+
当前创建接口支持普通的 `owner/name/input` 合同;视频 `schema_v2` 等高级参数后续接入。模型参数按 JSON 原样发送,不改写 prompt 或供应商。创建、查询和文本审核只发送一次请求,不自动轮询、重试、额外扣费或插入 Canva 设计。消费由应用显式调用具名方法。原有登录、额度和结账会话方法继续由同一个 hook 提供。
|
|
101
|
+
|
|
102
|
+
## 消费接口
|
|
103
|
+
|
|
104
|
+
三个具名方法复用 Provider 登录流程已获得的 passport,只提交指定的数量,原样返回账户服务的 `{ ok: 0, msg, ... }`。后端拒绝、非法响应、HTTP 失败、超时或取消会抛出 `ApiError`;`error.code` 保留后端的失败 `ok` 值。
|
|
105
|
+
|
|
106
|
+
| 方法 | 用途 | cnt 精度 |
|
|
107
|
+
| --- | --- | --- |
|
|
108
|
+
| `reduceFreeCnt` | 扣减免费次数 / 积分余额 `free_cnt` | 最多两位小数 |
|
|
109
|
+
| `addMonthlyUsage` | 累计订阅月用量 `monthly_usage_cnt` | 最多两位小数 |
|
|
110
|
+
| `addFreeUsageCnt` | 累计服务端计量模式的 `free_usage_cnt` | 最多一位小数 |
|
|
111
|
+
|
|
112
|
+
`cnt` 必须是有限的正数,并满足后端精度。应用按自己的计价规则、账户类型和剩余额度选择接口;方法不会自动选择套餐或拆分月额度与积分。下面是已确认本次消费应扣 `free_cnt` 时的组件示例:
|
|
113
|
+
|
|
114
|
+
```tsx
|
|
115
|
+
function ConfirmUsageButton() {
|
|
116
|
+
const client = useYiChongCanva();
|
|
117
|
+
const [busy, setBusy] = useState(false);
|
|
118
|
+
const [error, setError] = useState("");
|
|
119
|
+
|
|
120
|
+
async function confirmUsage() {
|
|
121
|
+
if (busy) return;
|
|
122
|
+
setBusy(true);
|
|
123
|
+
setError("");
|
|
124
|
+
try {
|
|
125
|
+
await client.reduceFreeCnt({ cnt: 1 });
|
|
126
|
+
await client.refreshUserStatus();
|
|
127
|
+
} catch (error) {
|
|
128
|
+
setError(error instanceof Error ? error.message : "消费未确认");
|
|
129
|
+
} finally {
|
|
130
|
+
setBusy(false);
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
return <>
|
|
135
|
+
<button disabled={busy || client.loginStatus !== "success"} onClick={() => void confirmUsage()}>
|
|
136
|
+
确认消费
|
|
137
|
+
</button>
|
|
138
|
+
{error && <p role="alert">{error}</p>}
|
|
139
|
+
</>;
|
|
140
|
+
}
|
|
141
|
+
```
|
|
142
|
+
|
|
143
|
+
月用量和服务端免费用量分别使用 `await client.addMonthlyUsage({ cnt: 1 })`、`await client.addFreeUsageCnt({ cnt: 1 })`,每次只调用业务所需的接口。确认后按需调用 `refreshUserStatus()` 更新显示;消费方法不会乐观修改余额,也不自动发起账户刷新。
|
|
144
|
+
|
|
145
|
+
默认消费超时为 30 秒,无自动重试。请求已发出后,超时、网络错误或取消不能证明服务端没有扣费;不要因此直接重放消费。后端未提供此接口的任务去重键,重复调用会再次记账。原有 `use()` 保留兼容,同一次消费不要同时调用 `use()` 和具名方法。
|
|
146
|
+
|
|
147
|
+
## Cloudflare R2 文件上传
|
|
148
|
+
|
|
149
|
+
`uploadFile({ file })` 自动完成上传:小于 100 MiB 使用单次 PUT,达到 100 MiB 使用分片。调用方式和返回值相同;也可传 `multipart: true` 让小文件使用分片,省略或 false 时按大小自动选择。它支持非空的 File / Blob,默认生成 `temp_<产品渠道>_<日期>_<随机值>.<扩展名>` 对象名,bucket 默认 `video`。可传 `objectName` 和 `bucketName` 指定存储位置;Blob 可通过 `fileName` 指定扩展名。
|
|
150
|
+
|
|
151
|
+
业务组件仍放在同一个 Provider 内:
|
|
152
|
+
|
|
153
|
+
```tsx
|
|
154
|
+
import { useEffect, useRef, useState } from "react";
|
|
155
|
+
import { useYiChongCanva } from "yichong-canva2";
|
|
70
156
|
|
|
71
|
-
|
|
157
|
+
function FileUploadPanel() {
|
|
158
|
+
const client = useYiChongCanva();
|
|
159
|
+
const [busy, setBusy] = useState(false);
|
|
160
|
+
const [url, setUrl] = useState("");
|
|
161
|
+
const [error, setError] = useState("");
|
|
72
162
|
|
|
73
|
-
|
|
163
|
+
const controllerRef = useRef<AbortController | null>(null);
|
|
164
|
+
useEffect(() => () => controllerRef.current?.abort(), []);
|
|
165
|
+
|
|
166
|
+
async function upload(file: File) {
|
|
167
|
+
if (controllerRef.current) return;
|
|
168
|
+
const controller = new AbortController();
|
|
169
|
+
controllerRef.current = controller;
|
|
170
|
+
setBusy(true);
|
|
171
|
+
setUrl("");
|
|
172
|
+
setError("");
|
|
173
|
+
try {
|
|
174
|
+
const uploaded = await client.uploadFile(
|
|
175
|
+
{ file }, // 大文件自动分片,无需自己切片。
|
|
176
|
+
{ signal: controller.signal },
|
|
177
|
+
);
|
|
178
|
+
setUrl(uploaded.url);
|
|
179
|
+
// 可以将 uploaded.url 放进 createSpecifyPrediction 的 input。
|
|
180
|
+
} catch (error) {
|
|
181
|
+
setError(error instanceof Error ? error.message : "上传失败");
|
|
182
|
+
} finally {
|
|
183
|
+
controllerRef.current = null;
|
|
184
|
+
setBusy(false);
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
return <>
|
|
189
|
+
<input
|
|
190
|
+
type="file"
|
|
191
|
+
disabled={busy || client.loginStatus !== "success"}
|
|
192
|
+
onChange={event => {
|
|
193
|
+
const file = event.target.files?.[0];
|
|
194
|
+
if (file) void upload(file);
|
|
195
|
+
}}
|
|
196
|
+
/>
|
|
197
|
+
<button disabled={!busy} onClick={() => controllerRef.current?.abort()}>取消上传</button>
|
|
198
|
+
{url && <a href={url} target="_blank" rel="noreferrer">查看上传文件</a>}
|
|
199
|
+
{error && <p role="alert">{error}</p>}
|
|
200
|
+
</>;
|
|
201
|
+
}
|
|
202
|
+
```
|
|
203
|
+
|
|
204
|
+
`generatePresignedUrl({ objectName, bucketName? })` 提供底层签名接口,返回后端原始结构;它本身不上传文件。一键上传必须取得合法的 `endpointBaseUrl` 才 PUT,避免把临时签名地址当成公开资源地址。旧响应仅返回签名 URL 时,底层方法仍可读取。
|
|
205
|
+
|
|
206
|
+
上传的整个流程共用一次超时和取消信号。单次 PUT 默认 120 秒,分片默认 30 分钟;可在第二个参数传 `{ signal, timeoutMs }` 调整。取消或账户、产品渠道变化后不再发起下一片或合并;合并请求已发出时,取消等待不能保证服务端没有完成。工具包不自动重试或续传。
|
|
207
|
+
|
|
208
|
+
分片顺序上传,默认每片 5 MiB,超大文件自动增大片大小以保持不超过 10000 片;最后一片可以更小。按 [R2 当前限制](https://developers.cloudflare.com/r2/platform/limits/) 校验文件大小(最多 5 TiB − 5 GiB)和对象名(最多 1024 个 UTF-8 字节),不将整份文件读入内存。
|
|
209
|
+
|
|
210
|
+
浏览器必须能读取每片 PUT 的 `ETag`。R2 bucket 的 CORS 要允许应用来源、`PUT` 和 `Content-Type`,并设置 `ExposeHeaders: ["ETag"]`,参见 [Cloudflare CORS 文档](https://developers.cloudflare.com/r2/buckets/cors/)。读取不到 ETag 时抛出 `code="missing_etag"`,停止上传,不会合并。
|
|
211
|
+
|
|
212
|
+
三个底层方法 `initiateUpload`、`getUploadUrl`、`completeUpload` 保留后端原始响应,使用上表中的参数,默认每次超时 60 秒。初始化结果的 `UploadId` 大写,下一步参数使用 `uploadId`;合并的 `parts` 必须按编号升序排列,每项使用后端要求的 `{ ETag, PartNumber }`,ETag 的引号原样保留。手动上传时由应用切片、PUT 和收集 ETag;一般业务直接使用 `uploadFile` 即可。
|
|
213
|
+
|
|
214
|
+
当前后端没有终止分片会话的接口,取消只停止客户端流程,已上传分片需由 bucket 的生命周期规则清理。[R2 官方文档](https://developers.cloudflare.com/r2/objects/upload-objects/) 说明默认会在 7 天后清理未完成会话,实际以当前 bucket 配置为准。
|
|
215
|
+
|
|
216
|
+
## 文本审核
|
|
217
|
+
|
|
218
|
+
`client.textCheck` 封装后端的公共文本审核接口,复用现有 Provider,无需另外配置令牌。请求发送到用户 JWT 公共入口。
|
|
219
|
+
|
|
220
|
+
```ts
|
|
221
|
+
const result = await client.textCheck(
|
|
222
|
+
{ text: userInput, scene: "default" },
|
|
223
|
+
{ timeoutMs: 30_000 },
|
|
224
|
+
);
|
|
225
|
+
|
|
226
|
+
if (result.data.allowed === true) {
|
|
227
|
+
// 可以继续后续操作;保留原始 decision,但不重复计算审核阈值。
|
|
228
|
+
} else {
|
|
229
|
+
// 在应用的提示组件中展示 result.msg。
|
|
230
|
+
}
|
|
231
|
+
```
|
|
232
|
+
|
|
233
|
+
应用只在 `data.allowed === true` 时继续。后端当前统一 `pass/review` 放行、`block` 拒绝;三种审核结果都可以是 HTTP 200 / `code=0`,它只表示审核执行成功。`msg`、`request_id`、`decision`、分类分数、`policy_version`、`model`、`duration_ms` 和附加字段原样保留。工具包严格验证 `allowed` 等响应字段,缺失或类型错误时抛出 `ApiError`。
|
|
234
|
+
|
|
235
|
+
`text` 必须非空,并同时满足最多 1024 个 Unicode 字符、1024 个 UTF-8 字节,例如 1024 个 ASCII 字符、341 个常见汉字或 256 个四字节 emoji。原文包含的空白会保留,不截断或拆片。`scene` 可省略,目前仅支持 `"default"`。本地非法参数抛出 `code="invalid_request"`,不会发送请求。
|
|
236
|
+
|
|
237
|
+
审核不会自动创建生成任务。上面的完整示例由应用显式先审核 prompt,再调用 `createSpecifyPrediction`;直接调用创建接口也不会隐式触发审核。
|
|
74
238
|
|
|
75
239
|
HTTP 失败、后端 `code` 非 `0`、网络错误、无效响应、超时和取消都会抛出导出的 `ApiError`。服务端返回的 `msg` 保留在 `error.message` / `error.userMessage`,应用应在错误组件中直接展示。`code=0` 且 `data.status="failed"` 表示任务执行失败,查询方法会保留任务信息,应用应处理 `error_msg` / `error`。
|
|
76
240
|
|
|
241
|
+
审核的技术错误也抛出 `ApiError`,不能当作审核通过。`error.status` / `error.code` 保留 HTTP 状态和后端 code;错误对象中的 `error.data` 保留后端 `error_code`、`request_id`、`retryable`、`allowed` 等字段。429 返回的 `Retry-After` 秒数保留在 `error.retryAfter`,由应用决定重试时机。
|
|
242
|
+
|
|
77
243
|
```ts
|
|
78
244
|
const controller = new AbortController();
|
|
79
245
|
const prediction = await client.getPrediction(
|
|
@@ -82,7 +248,59 @@ const prediction = await client.getPrediction(
|
|
|
82
248
|
);
|
|
83
249
|
```
|
|
84
250
|
|
|
85
|
-
取消只终止当前 HTTP
|
|
251
|
+
取消只终止当前 HTTP 等待,不会取消已经创建的后端任务或撤销已提交的消费。创建、查询、文本审核和底层签名的默认请求超时为 60 秒,包含读取响应正文的时间;消费为 30 秒,一键上传为 120 秒。
|
|
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` 不影响上报地址,调用方不能覆盖机器人、地址或令牌。
|
|
86
304
|
|
|
87
305
|
## 开发
|
|
88
306
|
|
|
@@ -93,6 +311,6 @@ npm run lint
|
|
|
93
311
|
npm test
|
|
94
312
|
```
|
|
95
313
|
|
|
96
|
-
`npm test` 构建后使用 Node
|
|
314
|
+
`npm test` 构建后使用 Node 测试真实产物,覆盖请求合同、消费数量精度、签名与 PUT 的凭据边界、错误、超时、取消,以及 Provider 登录/刷新后的凭据共享。测试替换 Canva 宿主和网络请求,不调用真实模型、记账或上传资源。
|
|
97
315
|
|
|
98
316
|
源码在 `packages/`,构建输出在 `dist/`。`npm run lint` 检查新增 API 模块和测试;全包类型由 `lint:types` 检查。原包的旧 Provider 实现暂时保留。
|
package/dist/api/error.js
CHANGED
|
@@ -1,10 +1,12 @@
|
|
|
1
1
|
class ApiError extends Error {
|
|
2
|
-
constructor(message, code, status) {
|
|
2
|
+
constructor(message, code, status, details) {
|
|
3
3
|
super(message);
|
|
4
4
|
this.code = code;
|
|
5
5
|
this.status = status;
|
|
6
6
|
this.name = "ApiError";
|
|
7
7
|
this.userMessage = message;
|
|
8
|
+
this.data = details == null ? void 0 : details.data;
|
|
9
|
+
this.retryAfter = details == null ? void 0 : details.retryAfter;
|
|
8
10
|
}
|
|
9
11
|
}
|
|
10
12
|
export {
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { ApiError } from "./error.js";
|
|
2
|
+
import { isObject, isNonemptyString, invalid, postApi } from "./request.js";
|
|
3
|
+
function isDecision(value) {
|
|
4
|
+
return value === "pass" || value === "review" || value === "block";
|
|
5
|
+
}
|
|
6
|
+
function isResult(value) {
|
|
7
|
+
return isObject(value) && typeof value.allowed === "boolean" && isDecision(value.decision) && isNonemptyString(value.request_id) && isNonemptyString(value.scene) && isNonemptyString(value.policy_version) && isNonemptyString(value.model) && typeof value.duration_ms === "number" && Number.isFinite(value.duration_ms) && value.duration_ms >= 0 && Array.isArray(value.flagged_categories) && value.flagged_categories.every(isNonemptyString) && isObject(value.categories) && Object.values(value.categories).every((category) => isObject(category) && typeof category.score === "number" && Number.isFinite(category.score) && category.score >= 0 && category.score <= 1 && isDecision(category.decision));
|
|
8
|
+
}
|
|
9
|
+
function createTextModerationApi(getContext) {
|
|
10
|
+
return {
|
|
11
|
+
async textCheck(params, options) {
|
|
12
|
+
if (!isObject(params) || !isNonemptyString(params.text) || params.scene !== void 0 && params.scene !== "default" || Object.keys(params).some((key) => key !== "text" && key !== "scene")) {
|
|
13
|
+
invalid("textCheck requires nonempty text and an optional default scene.");
|
|
14
|
+
}
|
|
15
|
+
if (/[\uD800-\uDFFF]/u.test(params.text)) invalid("text must contain valid Unicode characters.");
|
|
16
|
+
if ([...params.text].length > 1024 || new TextEncoder().encode(params.text).length > 1024) {
|
|
17
|
+
invalid("text must not exceed 1024 Unicode characters or 1024 UTF-8 bytes.");
|
|
18
|
+
}
|
|
19
|
+
const response = await postApi(getContext(), "textCheck", {
|
|
20
|
+
text: params.text,
|
|
21
|
+
...params.scene === void 0 ? {} : { scene: params.scene }
|
|
22
|
+
}, options);
|
|
23
|
+
if (!isResult(response.data)) {
|
|
24
|
+
throw new ApiError("Backend returned invalid text moderation information.", "invalid_response");
|
|
25
|
+
}
|
|
26
|
+
return response;
|
|
27
|
+
}
|
|
28
|
+
};
|
|
29
|
+
}
|
|
30
|
+
export {
|
|
31
|
+
createTextModerationApi
|
|
32
|
+
};
|
|
@@ -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
|
+
};
|