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