yichong-canva2 2.0.0 → 2.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 +124 -24
- package/dist/api/error.js +6 -0
- package/dist/api/predictions.js +25 -6
- package/dist/api/reporting.js +4 -2
- package/dist/api/request.js +1 -0
- package/dist/api/uploads.js +121 -11
- package/dist/api/usage.js +3 -4
- package/dist/login/account.js +69 -0
- package/dist/login/context.js +1 -0
- package/dist/login/login/apis/index.js +17 -13
- package/dist/login/login/apis/request.js +33 -4
- package/dist/login/login/login.js +111 -103
- package/dist/login/privider.js +191 -125
- package/dist/types/api/chat.d.ts +6 -1
- package/dist/types/api/content.d.ts +5 -1
- package/dist/types/api/error.d.ts +14 -2
- package/dist/types/api/index.d.ts +6 -1
- package/dist/types/api/moderation.d.ts +5 -1
- package/dist/types/api/predictions.d.ts +5 -1
- package/dist/types/api/reporting.d.ts +7 -0
- package/dist/types/api/reporting_payload.d.ts +6 -1
- package/dist/types/api/request.d.ts +40 -2
- package/dist/types/api/transport.d.ts +7 -1
- package/dist/types/api/types.d.ts +231 -22
- package/dist/types/api/uploads.d.ts +7 -0
- package/dist/types/api/usage.d.ts +7 -1
- package/dist/types/index.d.ts +5 -0
- package/dist/types/login/account.d.ts +36 -0
- package/dist/types/login/context.d.ts +36 -35
- package/dist/types/login/index.d.ts +1 -0
- package/dist/types/login/interface.d.ts +35 -2
- package/dist/types/login/login/apis/index.d.ts +35 -17
- package/dist/types/login/login/apis/request.d.ts +10 -6
- package/dist/types/login/login/interface.d.ts +10 -1
- package/dist/types/login/login/login.d.ts +43 -21
- package/dist/types/login/privider.d.ts +34 -21
- package/dist/types/login/use_canva.d.ts +5 -2
- package/dist/types/login/version.d.ts +6 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -2,10 +2,14 @@
|
|
|
2
2
|
|
|
3
3
|
使用一个 `YiChongCanvaProvider` 管理登录、订阅和额度,通过 `useYiChongCanva()` 直接调用后端接口。
|
|
4
4
|
|
|
5
|
+
`2.2.0` 新增账户请求超时、有限重试与自动飞书告警,公开 `accountError` 供 Footer 展示失败及重试;上报切换到最新指定的 webhook。
|
|
6
|
+
|
|
7
|
+
`2.1.0` 新增 `onUploadProgress` 和导出的 `UploadProgress` 类型,补齐视频目录参数,恢复消费数量原值透传,并将上传命名对齐旧随机算法与 MIME 后缀回退。上传继续复用 `ai.imgkits.com` 的四个 Cloudflare R2 接口,分片公开地址兼容旧响应,无需新增、迁移或部署后端接口。
|
|
8
|
+
|
|
5
9
|
## 使用
|
|
6
10
|
|
|
7
11
|
```sh
|
|
8
|
-
npm install yichong-canva2@2.
|
|
12
|
+
npm install yichong-canva2@2.2.0
|
|
9
13
|
```
|
|
10
14
|
|
|
11
15
|
`1.2.0` 新增文本审核、三个消费接口,以及 Cloudflare R2 单次和分片上传;继续复用原有 Provider。
|
|
@@ -82,7 +86,7 @@ function GenerateButton() {
|
|
|
82
86
|
|
|
83
87
|
`baseUrl` 沿用原有账户扣费接口的地址。预测和文本审核请求默认使用 `https://api.imgkits.com`,可以通过可选的 `apiBaseUrl` 指定测试地址。
|
|
84
88
|
|
|
85
|
-
文件签名服务默认使用 `https://ai.imgkits.com
|
|
89
|
+
文件签名服务默认使用 `https://ai.imgkits.com`,复用下表中的四个现有上传入口,可通过 Provider 的 `uploadBaseUrl` 指定测试服务。公开资源地址由后端响应的 `endpointBaseUrl` 提供:单次 PUT 使用普通签名响应;分片优先使用初始化响应,旧初始化响应缺少该字段时额外读取一次现有普通签名接口的地址信息,合并响应若提供最新地址则优先采用。`uploadBaseUrl` 是接口服务地址,不是公开资源地址。
|
|
86
90
|
|
|
87
91
|
内容提取默认使用 `https://ai.imgkits.com`,无需新增配置。Provider 可选的 `contentBaseUrl` 仅供覆盖测试服务地址;它独立于 `apiBaseUrl` 和 `uploadBaseUrl`,后者只控制上传签名服务。
|
|
88
92
|
|
|
@@ -104,10 +108,10 @@ function GenerateButton() {
|
|
|
104
108
|
| `client.addMonthlyUsage({ cnt })` | `POST {baseUrl}/api/user/add-monthly-usage` | `{ ok: 0, msg: "success" }` |
|
|
105
109
|
| `client.addFreeUsageCnt({ cnt })` | `POST {baseUrl}/api/user/add-free-usage-cnt` | `{ ok: 0, msg: "success" }` |
|
|
106
110
|
| `client.generatePresignedUrl({ objectName, bucketName? })` | `POST {uploadBaseUrl}/api/generate-presigned-url` | `{ success: true, url, endpointBaseUrl?, ... }` |
|
|
107
|
-
| `client.initiateUpload({ objectName, bucketName?, contentType? })` | `POST {uploadBaseUrl}/upload/initiate-upload` | `{ UploadId, Bucket?, Key?, ... }` |
|
|
111
|
+
| `client.initiateUpload({ objectName, bucketName?, contentType? })` | `POST {uploadBaseUrl}/upload/initiate-upload` | `{ UploadId, Bucket?, Key?, endpointBaseUrl?, ... }` |
|
|
108
112
|
| `client.getUploadUrl({ objectName, uploadId, partNumber, bucketName? })` | `POST {uploadBaseUrl}/upload/get-upload-url` | `{ url, ... }` |
|
|
109
|
-
| `client.completeUpload({ objectName, uploadId, parts, bucketName? })` | `POST {uploadBaseUrl}/upload/complete-upload` | `{ ETag, Bucket?, Key?, Location?, ... }` |
|
|
110
|
-
| `client.uploadFile({ file, ... })` | 自动单次 PUT 或初始化 → 分片签名 / PUT →
|
|
113
|
+
| `client.completeUpload({ objectName, uploadId, parts, bucketName? })` | `POST {uploadBaseUrl}/upload/complete-upload` | `{ ETag, Bucket?, Key?, Location?, endpointBaseUrl?, ... }` |
|
|
114
|
+
| `client.uploadFile({ file, onUploadProgress?, ... })` | 自动单次 PUT 或初始化 → 获取公开地址 → 分片签名 / PUT → 合并;从 2.1.0 支持进度回调 | `{ url: "公开资源地址", key, endpointBaseUrl }` |
|
|
111
115
|
|
|
112
116
|
Provider 自动注入自有后端请求 query 中的 `uid`、`platform_uid`、`platform=canva_addon`、`app_channel`、`timezone`,以及请求头 `Accept-Language`。时区每次请求通过 `Intl.DateTimeFormat().resolvedOptions().timeZone` 读取,如 `Asia/Taipei`;运行环境不支持时使用 `UTC`。浏览器请求不额外发送 `accept_language` 参数。
|
|
113
117
|
|
|
@@ -115,19 +119,19 @@ Provider 自动注入自有后端请求 query 中的 `uid`、`platform_uid`、`p
|
|
|
115
119
|
|
|
116
120
|
预测、文本审核、内容提取和大模型 `chat` 还携带 `Authorization: Bearer <jwt>`、`Channel: ai`;具名消费接口使用 `X-Access-Ticket`、`X-Access-Channel`;签名接口使用 `Channel: node-nauth`。R2 PUT 原样使用签名 URL,只携带文件的 `Content-Type`;错误上报 Worker 使用独立协议,身份与渠道信息放在诊断消息中。创建请求中的 `user_id` 使用系统用户 ID(`userStatus.profile.id`)。公共审核只要求有效的业务 JWT;`uid` 和 `platform_uid` 在账户状态包含这些值时才附带,审核身份由后端验签确定。
|
|
117
121
|
|
|
118
|
-
|
|
122
|
+
创建接口保留普通的 `owner/name/input` 合同,也支持后端现有的 `video_type`、`video_catalog`、`catalog_model_id`、`primary_provider`、`execution_chain`、`provider_requests` 参数;这些视频路由字段按原名和 JSON 结构传递。当 `video_catalog: "schema_v2"` 且 `provider_requests` 非空时,可省略顶层 `input`,由各供应商请求携带输入;普通任务仍须传 `input` 对象。SDK 不改写 prompt、选择供应商或调整执行链。创建、查询和文本审核只发送一次请求,不自动轮询、重试、额外扣费或插入 Canva 设计。消费由应用显式调用具名方法。原有登录、额度和结账会话方法继续由同一个 hook 提供。
|
|
119
123
|
|
|
120
124
|
## 消费接口
|
|
121
125
|
|
|
122
126
|
三个具名方法复用 Provider 登录流程已获得的 passport,只提交指定的数量,原样返回账户服务的 `{ ok: 0, msg, ... }`。后端拒绝、非法响应、HTTP 失败、超时或取消会抛出 `ApiError`;`error.code` 保留后端的失败 `ok` 值。
|
|
123
127
|
|
|
124
|
-
| 方法 | 用途 |
|
|
128
|
+
| 方法 | 用途 | 后端记账精度 |
|
|
125
129
|
| --- | --- | --- |
|
|
126
|
-
| `reduceFreeCnt` | 扣减免费次数 / 积分余额 `free_cnt` |
|
|
127
|
-
| `addMonthlyUsage` | 累计订阅月用量 `monthly_usage_cnt` |
|
|
128
|
-
| `addFreeUsageCnt` | 累计服务端计量模式的 `free_usage_cnt` |
|
|
130
|
+
| `reduceFreeCnt` | 扣减免费次数 / 积分余额 `free_cnt` | 四舍五入到两位小数 |
|
|
131
|
+
| `addMonthlyUsage` | 累计订阅月用量 `monthly_usage_cnt` | 四舍五入到两位小数 |
|
|
132
|
+
| `addFreeUsageCnt` | 累计服务端计量模式的 `free_usage_cnt` | 四舍五入到一位小数 |
|
|
129
133
|
|
|
130
|
-
`cnt`
|
|
134
|
+
`cnt` 必须是有限的正数,并在安全数值范围内。SDK 原样提交,不因超过一位/两位小数而拒绝,也不在前端舍入;例如 `reduceFreeCnt({ cnt: 1.234 })` 发送 `1.234`,由后端按两位小数处理。应用按自己的计价规则、账户类型和剩余额度选择接口;方法不会自动选择套餐或拆分月额度与积分。下面是已确认本次消费应扣 `free_cnt` 时的组件示例:
|
|
131
135
|
|
|
132
136
|
```tsx
|
|
133
137
|
function ConfirmUsageButton() {
|
|
@@ -164,42 +168,122 @@ function ConfirmUsageButton() {
|
|
|
164
168
|
|
|
165
169
|
## Cloudflare R2 文件上传
|
|
166
170
|
|
|
167
|
-
`
|
|
171
|
+
`2.1.0` 增加分片公开地址兼容处理和 `onUploadProgress`,继续复用 `ai.imgkits.com` 的现有接口,无需新增或部署后端。这里只接入 Cloudflare R2;`aliyun-fc` 是签名服务的托管平台,与文件存储不同,本次不接入阿里云 OSS,也不改变现有托管平台。
|
|
172
|
+
|
|
173
|
+
`uploadFile({ file })` 自动完成上传:小于 100 MiB 使用单次 PUT,达到 100 MiB 使用分片。调用方式和返回值相同;也可传 `multipart: true` 让小文件使用分片,省略或 false 时按大小自动选择。它支持非空的 File / Blob,默认生成 `temp_{app_channel}_{YYYY-MM-DD}_{32位随机}.{后缀}` 对象名:`app_channel` 对应 Provider 的 `productName`,日期使用浏览器本地日期,随机部分沿用旧应用的 `randomString(32)`:使用 `Math.random()` 从固定字符集 `ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678` 中逐位取值。bucket 默认 `video`。显式传入 `objectName` 时使用指定对象名,不套用默认命名格式;可传 `bucketName` 指定 bucket,Blob 可通过 `fileName` 指定扩展名;未提供文件后缀时沿用旧模板的 MIME subtype 回退(例如 `audio/wav` → `wav`、`video/webm` → `webm`),均缺失才使用 `bin`。
|
|
174
|
+
|
|
175
|
+
单次上传先获取普通签名,再 PUT 文件,公开地址由签名响应的 `endpointBaseUrl` 生成。分片先调用 `initiateUpload`:响应已有 `endpointBaseUrl` 时直接使用;旧初始化响应未返回该字段时,用相同的对象名和 bucket 调用一次现有 `generatePresignedUrl`,只读取响应中的 `endpointBaseUrl`。这次额外请求是为了取得旧分片响应缺少的公开地址信息;返回的整文件签名 URL 不用于上传分片。取得并校验有效的公开 HTTPS 基础地址后,再逐片 `getUploadUrl` / PUT,最后 `completeUpload`。
|
|
176
|
+
|
|
177
|
+
合并响应若提供 `endpointBaseUrl`,则以它的最新地址为准;未提供时保留初始化或兼容请求取得的地址。返回的 `endpointBaseUrl` 是最终采用的地址,两种方式都按对象路径段编码生成 `url`,`key` 保留原对象名。初始化响应提供了非法地址,或兼容签名响应缺少有效地址时,抛出 `invalid_response` 且不开始 PUT;合并响应提供非法地址也会报错。SDK 不从 S3 `Location` 或签名 URL 的 host 推测公开地址,也没有客户端固定域名兜底。
|
|
178
|
+
|
|
179
|
+
前端不新增存储密钥;请求继续使用 `Channel: node-nauth` 和通用 query 参数。公开地址始终采用后端返回值,不要求本次增加后端配置或迁移接口。
|
|
180
|
+
|
|
181
|
+
将 `onUploadProgress` 放在第一个参数中,其参数是导出的 `UploadProgress` 类型:`{ loaded: number, total?: number }`。单位沿用旧工具:单次 PUT 使用浏览器 XHR 的真实上传字节数;分片在每片 PUT 成功并取得 ETag 后通知已完成片数和总片数。应用用 `loaded / total` 驱动比例,不把所有进度都标成字节;浏览器无法确定单次总量时省略 `total`,界面应显示不定进度。未传回调时单次 PUT 继续使用 fetch。
|
|
182
|
+
|
|
183
|
+
100% 只表示传输进度,不代表服务端响应或分片合并成功;仍需 `await client.uploadFile(...)` 后使用公开 URL。取消或失败后停止通知;回调抛错会终止上传并抛出 `code="upload_progress_failed"`,回调中不应自行抛错作为普通状态更新。
|
|
184
|
+
|
|
185
|
+
**普通上传**(小于 100 MiB,且未强制分片):
|
|
186
|
+
|
|
187
|
+
```mermaid
|
|
188
|
+
sequenceDiagram
|
|
189
|
+
participant C as 浏览器/工具包
|
|
190
|
+
participant B as 原上传后端
|
|
191
|
+
participant R as Cloudflare R2
|
|
192
|
+
|
|
193
|
+
C->>B: generatePresignedUrl<br/>POST /api/generate-presigned-url
|
|
194
|
+
B-->>C: PUT 签名地址 + endpointBaseUrl
|
|
195
|
+
C->>R: 向签名地址 PUT 整个文件
|
|
196
|
+
Note over C,R: 传入进度回调时,按上传字节数报告进度
|
|
197
|
+
R-->>C: 上传成功
|
|
198
|
+
Note over C: 返回公开 URL、key、endpointBaseUrl
|
|
199
|
+
```
|
|
200
|
+
|
|
201
|
+
**分片上传**(达到 100 MiB,或显式传入 `multipart: true`):
|
|
202
|
+
|
|
203
|
+
```mermaid
|
|
204
|
+
sequenceDiagram
|
|
205
|
+
participant C as 浏览器/工具包
|
|
206
|
+
participant B as 原上传后端
|
|
207
|
+
participant R as Cloudflare R2
|
|
208
|
+
|
|
209
|
+
C->>B: initiateUpload<br/>POST /upload/initiate-upload
|
|
210
|
+
B-->>C: UploadId + 可选 endpointBaseUrl
|
|
211
|
+
|
|
212
|
+
opt 初始化未返回公开域名
|
|
213
|
+
C->>B: generatePresignedUrl
|
|
214
|
+
B-->>C: 读取 endpointBaseUrl
|
|
215
|
+
Note over C: 仅取得公开域名<br/>不使用这次整文件 PUT 签名上传
|
|
216
|
+
end
|
|
217
|
+
|
|
218
|
+
Note over C: 文件切片,通常每片 5 MiB
|
|
219
|
+
loop 按顺序上传每一片
|
|
220
|
+
C->>B: getUploadUrl<br/>POST /upload/get-upload-url
|
|
221
|
+
B-->>C: 当前分片的 PUT 签名地址
|
|
222
|
+
C->>R: PUT 当前分片
|
|
223
|
+
R-->>C: 返回 ETag
|
|
224
|
+
Note over C: 保存 ETag,回调完成片数/总片数
|
|
225
|
+
end
|
|
226
|
+
|
|
227
|
+
Note over C: 此时进度 100%,仍需等待合并
|
|
228
|
+
C->>B: completeUpload<br/>POST /upload/complete-upload<br/>提交片号和 ETag 清单
|
|
229
|
+
B->>R: 合并分片
|
|
230
|
+
R-->>B: 合并成功
|
|
231
|
+
B-->>C: ETag + 可选 endpointBaseUrl
|
|
232
|
+
Note over C: 返回公开 URL、key、endpointBaseUrl
|
|
233
|
+
```
|
|
168
234
|
|
|
169
|
-
|
|
235
|
+
图中的原上传后端默认是 `https://ai.imgkits.com`。分片公开地址优先级为:合并响应提供的新地址 → 初始化响应地址 → 初始化缺失时从现有签名接口补取的地址;取得无效地址会报错,不猜测或硬编码域名。图示是成功流程,进度达到 100% 仍须等待 `uploadFile` 的 Promise 成功。
|
|
236
|
+
|
|
237
|
+
业务组件仍放在同一个 Provider 内,直接调用 `client.uploadFile`。下面根据比例展示进度,在 Promise 完成后才显示结果:
|
|
170
238
|
|
|
171
239
|
```tsx
|
|
172
240
|
import { useEffect, useRef, useState } from "react";
|
|
173
|
-
import { useYiChongCanva } from "yichong-canva2";
|
|
241
|
+
import { useYiChongCanva, type UploadProgress } from "yichong-canva2";
|
|
174
242
|
|
|
175
243
|
function FileUploadPanel() {
|
|
176
244
|
const client = useYiChongCanva();
|
|
177
245
|
const [busy, setBusy] = useState(false);
|
|
246
|
+
const [progress, setProgress] = useState<number>();
|
|
178
247
|
const [url, setUrl] = useState("");
|
|
179
248
|
const [error, setError] = useState("");
|
|
180
249
|
|
|
181
250
|
const controllerRef = useRef<AbortController | null>(null);
|
|
182
|
-
useEffect(() => () =>
|
|
251
|
+
useEffect(() => () => {
|
|
252
|
+
controllerRef.current?.abort();
|
|
253
|
+
controllerRef.current = null;
|
|
254
|
+
}, []);
|
|
183
255
|
|
|
184
256
|
async function upload(file: File) {
|
|
185
257
|
if (controllerRef.current) return;
|
|
186
258
|
const controller = new AbortController();
|
|
187
259
|
controllerRef.current = controller;
|
|
188
260
|
setBusy(true);
|
|
261
|
+
setProgress(undefined);
|
|
189
262
|
setUrl("");
|
|
190
263
|
setError("");
|
|
191
264
|
try {
|
|
192
265
|
const uploaded = await client.uploadFile(
|
|
193
|
-
{
|
|
266
|
+
{
|
|
267
|
+
file, // 大文件自动分片;小文件也可加 multipart: true。
|
|
268
|
+
onUploadProgress: ({ loaded, total }: UploadProgress) => {
|
|
269
|
+
if (controllerRef.current !== controller) return;
|
|
270
|
+
setProgress(total && total > 0 ? Math.min(100, loaded / total * 100) : undefined);
|
|
271
|
+
},
|
|
272
|
+
},
|
|
194
273
|
{ signal: controller.signal },
|
|
195
274
|
);
|
|
275
|
+
if (controllerRef.current !== controller) return;
|
|
196
276
|
setUrl(uploaded.url);
|
|
197
|
-
//
|
|
277
|
+
// Promise 完成才表示上传成功;进度 100% 不能替代此确认。
|
|
198
278
|
} catch (error) {
|
|
199
|
-
|
|
279
|
+
if (controllerRef.current === controller) {
|
|
280
|
+
setError(controller.signal.aborted ? "已取消上传" : error instanceof Error ? error.message : "上传失败");
|
|
281
|
+
}
|
|
200
282
|
} finally {
|
|
201
|
-
controllerRef.current
|
|
202
|
-
|
|
283
|
+
if (controllerRef.current === controller) {
|
|
284
|
+
controllerRef.current = null;
|
|
285
|
+
setBusy(false);
|
|
286
|
+
}
|
|
203
287
|
}
|
|
204
288
|
}
|
|
205
289
|
|
|
@@ -213,13 +297,15 @@ function FileUploadPanel() {
|
|
|
213
297
|
}}
|
|
214
298
|
/>
|
|
215
299
|
<button disabled={!busy} onClick={() => controllerRef.current?.abort()}>取消上传</button>
|
|
300
|
+
{busy && <progress max={100} value={progress} aria-label="上传进度" />}
|
|
301
|
+
{busy && <p>{progress === undefined ? "正在上传…" : progress >= 100 ? "等待上传确认…" : `${Math.floor(progress)}%`}</p>}
|
|
216
302
|
{url && <a href={url} target="_blank" rel="noreferrer">查看上传文件</a>}
|
|
217
303
|
{error && <p role="alert">{error}</p>}
|
|
218
304
|
</>;
|
|
219
305
|
}
|
|
220
306
|
```
|
|
221
307
|
|
|
222
|
-
`generatePresignedUrl({ objectName, bucketName? })`
|
|
308
|
+
`generatePresignedUrl({ objectName, bucketName? })` 提供底层签名接口,返回后端原始结构;它本身不上传文件。一键单次上传必须取得合法的 `endpointBaseUrl` 才 PUT,避免把临时签名地址当成公开资源地址。旧响应仅返回签名 URL 时,底层方法仍可读取;一键分片在初始化响应缺少公开地址时也会调用该方法,只使用其 `endpointBaseUrl`。
|
|
223
309
|
|
|
224
310
|
上传的整个流程共用一次超时和取消信号。单次 PUT 默认 120 秒,分片默认 30 分钟;可在第二个参数传 `{ signal, timeoutMs }` 调整。取消或账户、产品渠道变化后不再发起下一片或合并;合并请求已发出时,取消等待不能保证服务端没有完成。工具包不自动重试或续传。
|
|
225
311
|
|
|
@@ -227,7 +313,7 @@ function FileUploadPanel() {
|
|
|
227
313
|
|
|
228
314
|
浏览器必须能读取每片 PUT 的 `ETag`。R2 bucket 的 CORS 要允许应用来源、`PUT` 和 `Content-Type`,并设置 `ExposeHeaders: ["ETag"]`,参见 [Cloudflare CORS 文档](https://developers.cloudflare.com/r2/buckets/cors/)。读取不到 ETag 时抛出 `code="missing_etag"`,停止上传,不会合并。
|
|
229
315
|
|
|
230
|
-
三个底层方法 `initiateUpload`、`getUploadUrl`、`completeUpload` 保留后端原始响应,使用上表中的参数,默认每次超时 60
|
|
316
|
+
三个底层方法 `initiateUpload`、`getUploadUrl`、`completeUpload` 保留后端原始响应,使用上表中的参数,默认每次超时 60 秒。为兼容历史直接调用,`initiateUpload` 和 `completeUpload` 的响应类型仍将 `endpointBaseUrl` 定义为可选字段;一键 `uploadFile` 会在旧初始化响应缺少该字段时通过现有签名接口补取,不需要后端新增字段才能上传。初始化结果的 `UploadId` 大写,下一步参数使用 `uploadId`;合并的 `parts` 必须按编号升序排列,每项使用后端要求的 `{ ETag, PartNumber }`,ETag 的引号原样保留。手动上传时由应用切片、PUT 和收集 ETag;一般业务直接使用 `uploadFile` 即可。
|
|
231
317
|
|
|
232
318
|
当前后端没有终止分片会话的接口,取消只停止客户端流程,已上传分片需由 bucket 的生命周期规则清理。[R2 官方文档](https://developers.cloudflare.com/r2/objects/upload-objects/) 说明默认会在 7 天后清理未完成会话,实际以当前 bucket 配置为准。
|
|
233
319
|
|
|
@@ -387,9 +473,23 @@ const prediction = await client.getPrediction(
|
|
|
387
473
|
|
|
388
474
|
取消只终止当前 HTTP 等待,不会取消已经创建的后端任务或撤销已提交的消费。创建、查询、文本审核和底层签名的默认请求超时为 60 秒,包含读取响应正文的时间;内容提取和大模型 `chat` 为 360 秒,消费为 30 秒,单次 PUT 上传为 120 秒,分片上传整体为 30 分钟。
|
|
389
475
|
|
|
476
|
+
## 账户故障处理(2.2.0)
|
|
477
|
+
|
|
478
|
+
继续使用一个 `YiChongCanvaProvider`,无需额外的上报 Provider 或 Footer 上报包装。账户模块会自动报告最终失败,业务 API 的错误仍在业务 catch 中按需显式调用 `client.reportError`。
|
|
479
|
+
|
|
480
|
+
- Canva token、身份验证、canvaid-login、passport 和 status 每步最多 10 秒(含响应正文)。首次登录及其重试共享 30 秒预算;`retry` 仍决定额外尝试次数,但不能突破总预算。
|
|
481
|
+
- 登录最终失败后 `loginStatus` 变为 `error`,Footer 停止圆圈并保留原 `Connect account` 重试按钮。`client.manualLogin()` 开始新一轮;取消旧请求和计时器,迟到响应不再更新状态。
|
|
482
|
+
- `client.refreshUserStatus()` 最多两次尝试,共享 30 秒;失败仍返回旧快照以兼容已有调用,同时设置 `client.accountError`。未登录时只返回当前快照,不抢占登录。返回快照不等于刷新成功,也不能据此认定消费成功。
|
|
483
|
+
- 支付轮询保留原快慢间隔和默认五分钟 TTL;连续三次网络/服务器故障提前结束,确定的响应/业务错误直接结束。健康的状态未变化、正常 TTL 或主动停止不告警;收尾补刷真实失败仍报告。补刷最多 10 秒并取消超时请求。
|
|
484
|
+
- `accountError` 为只读诊断快照或 `null`,包含 `operation`(login/refresh/poll)、`stage`、`code`、可用的 HTTP `status`、安全诊断 `message`、阶段尝试数 `attempts`、耗时 `elapsedMs` 和不带查询参数的 `api`。应用应根据状态显示本地化文案,不直接展示技术诊断。开始重试或成功后清除。
|
|
485
|
+
- Provider 按应用、接口、错误类型五分钟去重。自动报告不等待发送完成,发送失败不影响界面、不递归上报;卸载、主动取消、旧流程被替换都不告警。无需全局异常监听。
|
|
486
|
+
- 上报复用 `https://report.imgkits.com` 的现有转发协议,目标采用最新指定的 webhook,并携带应用/工具包版本。SDK 只收集必要的诊断字段,不发送 JWT、passport、查询参数或原始服务端正文。完全断网时不能保证告警送达。
|
|
487
|
+
|
|
488
|
+
脚手架 Footer 只读取状态、展示新增失败提示和调用已有重试方法,不自行发送账户报告。正常七种额度文案、样式和布局保持原样。已有应用需要升级 SDK,并同步 Footer 的错误展示分支;更新脚手架不会自动改写旧应用。
|
|
489
|
+
|
|
390
490
|
## 错误上报
|
|
391
491
|
|
|
392
|
-
继续使用同一个 Provider,业务代码直接调用 `client.reportError`。`error` 接受 Error、ApiError、字符串或其他被抛出的值。Provider 自动补充产品渠道、应用 ID、应用版本及可用的用户 ID。工具包内置现有 Worker
|
|
492
|
+
继续使用同一个 Provider,业务代码直接调用 `client.reportError`。`error` 接受 Error、ApiError、字符串或其他被抛出的值。Provider 自动补充产品渠道、应用 ID、应用版本及可用的用户 ID。工具包内置现有 Worker 地址和固定上报令牌,通过 Worker 原有 `robot` 字段指定最新约定的飞书 webhook(业务应用无需再配置),应用无需新增配置或修改后端。
|
|
393
493
|
|
|
394
494
|
固定令牌会随 npm 包和应用浏览器产物公开,不能视为保密凭据。此请求不向 Worker 发送用户 JWT 或 passport;这类值会从诊断正文中移除。上报可在 Provider 登录前调用,尚未获得的用户 ID 标为 unknown。
|
|
395
495
|
|
|
@@ -435,7 +535,7 @@ function GenerateButton() {
|
|
|
435
535
|
|
|
436
536
|
`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 和处理阶段,避免传原始用户输入或文件。
|
|
437
537
|
|
|
438
|
-
成功原样返回 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
|
|
538
|
+
成功原样返回 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 错误监听。账户登录、刷新和支付检查的最终失败由 Provider 自动上报;其它业务 API 的失败仍由业务显式调用。
|
|
439
539
|
|
|
440
540
|
默认超时 10 秒,支持第二参数 `{ signal, timeoutMs }`,只请求一次。沿用 Worker 的噪声过滤规则,本次不新增服务端限流或网关转发。上报失败不要再次上报自身异常;缺少 Provider 时抛出 provider_missing。`apiBaseUrl` 不影响上报地址,调用方不能覆盖机器人、地址或令牌。
|
|
441
541
|
|
package/dist/api/error.js
CHANGED
|
@@ -1,4 +1,10 @@
|
|
|
1
1
|
class ApiError extends Error {
|
|
2
|
+
/**
|
|
3
|
+
* @param message 可展示的错误说明。
|
|
4
|
+
* @param code 后端业务码或 SDK 标识,例如 invalid_request、timeout、network_error。
|
|
5
|
+
* @param status 已取得的 HTTP 状态;请求发出前的错误等情况通常没有此值。
|
|
6
|
+
* @param details 可选诊断数据和 Retry-After 秒数;仅提供信息,不触发重试。
|
|
7
|
+
*/
|
|
2
8
|
constructor(message, code, status, details) {
|
|
3
9
|
super(message);
|
|
4
10
|
this.code = code;
|
package/dist/api/predictions.js
CHANGED
|
@@ -3,14 +3,33 @@ import { isObject, isNonemptyString, invalid, postApi, validateJson } from "./re
|
|
|
3
3
|
function createPredictionApi(getContext) {
|
|
4
4
|
return {
|
|
5
5
|
async createSpecifyPrediction(params, options) {
|
|
6
|
-
|
|
7
|
-
|
|
6
|
+
var _a;
|
|
7
|
+
if (!isObject(params) || !isNonemptyString(params.owner) || !isNonemptyString(params.name)) {
|
|
8
|
+
invalid("createSpecifyPrediction requires owner and name.");
|
|
8
9
|
}
|
|
9
|
-
|
|
10
|
-
|
|
10
|
+
const keys = ["owner", "name", "input", "video_type", "video_catalog", "catalog_model_id", "primary_provider", "execution_chain", "provider_requests"];
|
|
11
|
+
if (Object.keys(params).some((key) => !keys.some((allowed) => allowed === key))) {
|
|
12
|
+
invalid("createSpecifyPrediction received unsupported parameters.");
|
|
11
13
|
}
|
|
12
|
-
|
|
13
|
-
|
|
14
|
+
for (const key of ["video_type", "video_catalog", "catalog_model_id", "primary_provider"]) {
|
|
15
|
+
if (params[key] !== void 0 && typeof params[key] !== "string") invalid(`${key} must be a string.`);
|
|
16
|
+
}
|
|
17
|
+
if (params.execution_chain !== void 0 && (!Array.isArray(params.execution_chain) || ![...params.execution_chain].every((value) => typeof value === "string"))) {
|
|
18
|
+
invalid("execution_chain must be an array of provider names.");
|
|
19
|
+
}
|
|
20
|
+
if (params.provider_requests !== void 0 && (!Array.isArray(params.provider_requests) || ![...params.provider_requests].every(isObject))) {
|
|
21
|
+
invalid("provider_requests must be an array of request objects.");
|
|
22
|
+
}
|
|
23
|
+
const hasProviderRequests = params.video_catalog === "schema_v2" && (((_a = params.provider_requests) == null ? void 0 : _a.length) ?? 0) > 0;
|
|
24
|
+
if (!isObject(params.input) && !(params.input === void 0 && hasProviderRequests)) {
|
|
25
|
+
invalid("input must be an object unless schema_v2 provides provider_requests.");
|
|
26
|
+
}
|
|
27
|
+
const body = {};
|
|
28
|
+
for (const key of keys) {
|
|
29
|
+
if (params[key] !== void 0) body[key] = params[key];
|
|
30
|
+
}
|
|
31
|
+
validateJson(body);
|
|
32
|
+
const response = await postApi(getContext(), "createSpecifyPrediction", body, options);
|
|
14
33
|
if (!isNonemptyString(response.data)) throw new ApiError("Create response did not contain a prediction ID.", "invalid_response");
|
|
15
34
|
return response;
|
|
16
35
|
},
|
package/dist/api/reporting.js
CHANGED
|
@@ -2,6 +2,7 @@ import { ApiError } from "./error.js";
|
|
|
2
2
|
import { isNonemptyString, invalid, readJson, isObject, backendError } from "./request.js";
|
|
3
3
|
import { reportingPayload } from "./reporting_payload.js";
|
|
4
4
|
import { withRequest } from "./transport.js";
|
|
5
|
+
const reportRobot = "https://open.feishu.cn/open-apis/bot/v2/hook/c32b7f2a-d17a-478f-8a42-c9226b0a7e11";
|
|
5
6
|
const reportUrl = "https://report.imgkits.com";
|
|
6
7
|
const reportToken = "base64:MsUJo+qAhIVGPx52r1mbxCYn5YbWtCx8FQ7pTaHEvRo=";
|
|
7
8
|
function createErrorReportingApi(getContext) {
|
|
@@ -12,13 +13,14 @@ function createErrorReportingApi(getContext) {
|
|
|
12
13
|
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
14
|
invalid("Error reporting requires the Provider productName, appId and version.");
|
|
14
15
|
}
|
|
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 secrets = [reportToken, reportRobot, 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
17
|
const details = {
|
|
17
18
|
time: (/* @__PURE__ */ new Date()).toISOString(),
|
|
18
19
|
app_channel: context.productName,
|
|
19
20
|
platform: "canva_addon",
|
|
20
21
|
app_id: context.appId,
|
|
21
22
|
app_version: String(context.version),
|
|
23
|
+
sdk_version: "2.2.0",
|
|
22
24
|
user_id: ((_c = context.userStatus.profile) == null ? void 0 : _c.id) ?? "unknown",
|
|
23
25
|
platform_uid: context.userStatus.userId ?? "unknown",
|
|
24
26
|
...reportingPayload(params, secrets)
|
|
@@ -28,7 +30,7 @@ function createErrorReportingApi(getContext) {
|
|
|
28
30
|
if (secret.length >= 4) message = message.split(secret).join("[redacted]");
|
|
29
31
|
}
|
|
30
32
|
message = message.replace(/</g, "<").replace(/>/g, ">");
|
|
31
|
-
const body = JSON.stringify({ robot:
|
|
33
|
+
const body = JSON.stringify({ robot: reportRobot, title: "Canva 应用错误", titleColor: "red", message });
|
|
32
34
|
if (new TextEncoder().encode(body).length > 16384) invalid("Error report is too large; provide a smaller context.");
|
|
33
35
|
return withRequest({ ...options, timeoutMs: (options == null ? void 0 : options.timeoutMs) ?? 1e4 }, async (signal) => {
|
|
34
36
|
const response = await fetch(reportUrl, {
|
package/dist/api/request.js
CHANGED
|
@@ -99,6 +99,7 @@ async function postApi(context, method, params, options = {}) {
|
|
|
99
99
|
Authorization: `Bearer ${userStatus.jwt}`,
|
|
100
100
|
Channel: "ai"
|
|
101
101
|
},
|
|
102
|
+
// 创建任务还需在正文写入 user_id,始终以 Provider 账号为准。
|
|
102
103
|
body: JSON.stringify(method === "createSpecifyPrediction" ? { ...params, user_id: uid } : params),
|
|
103
104
|
signal,
|
|
104
105
|
credentials: "omit",
|
package/dist/api/uploads.js
CHANGED
|
@@ -58,6 +58,7 @@ async function initiate(context, params, signal) {
|
|
|
58
58
|
contentType: params.contentType
|
|
59
59
|
}, signal);
|
|
60
60
|
if (!isNonemptyString(payload.UploadId)) throw new ApiError("Backend did not return UploadId.", "invalid_response");
|
|
61
|
+
if (payload.endpointBaseUrl !== void 0) httpsUrl(payload.endpointBaseUrl, true);
|
|
61
62
|
return payload;
|
|
62
63
|
}
|
|
63
64
|
async function partUrl(context, params, signal) {
|
|
@@ -89,6 +90,7 @@ async function complete(context, params, signal) {
|
|
|
89
90
|
parts
|
|
90
91
|
}, signal);
|
|
91
92
|
if (!isNonemptyString(payload.ETag)) throw new ApiError("Backend did not confirm multipart completion with ETag.", "invalid_response");
|
|
93
|
+
if (payload.endpointBaseUrl !== void 0) httpsUrl(payload.endpointBaseUrl, true);
|
|
92
94
|
return payload;
|
|
93
95
|
}
|
|
94
96
|
function httpsUrl(value, publicBase = false) {
|
|
@@ -98,7 +100,7 @@ function httpsUrl(value, publicBase = false) {
|
|
|
98
100
|
} catch {
|
|
99
101
|
throw new ApiError("Backend returned an invalid upload URL.", "invalid_response");
|
|
100
102
|
}
|
|
101
|
-
if (url.protocol !== "https:" || url.username || url.password || url.hash || publicBase && url.
|
|
103
|
+
if (url.protocol !== "https:" || url.username || url.password || url.hash || publicBase && /[?#]/.test(url.href)) {
|
|
102
104
|
throw new ApiError("Upload URLs must be HTTPS without credentials or fragments.", "invalid_response");
|
|
103
105
|
}
|
|
104
106
|
return url;
|
|
@@ -133,13 +135,97 @@ async function presign(context, params, signal) {
|
|
|
133
135
|
if (payload.endpointBaseUrl !== void 0) httpsUrl(payload.endpointBaseUrl, true);
|
|
134
136
|
return payload;
|
|
135
137
|
}
|
|
138
|
+
function putWithProgress(url, file, contentType, signal, onProgress, check) {
|
|
139
|
+
if (typeof XMLHttpRequest === "undefined") {
|
|
140
|
+
throw new ApiError("Upload progress requires a browser with XMLHttpRequest.", "unsupported_environment");
|
|
141
|
+
}
|
|
142
|
+
return new Promise((resolve, reject) => {
|
|
143
|
+
const xhr = new XMLHttpRequest();
|
|
144
|
+
let settled = false;
|
|
145
|
+
const cleanup = () => {
|
|
146
|
+
signal.removeEventListener("abort", onAbort);
|
|
147
|
+
xhr.upload.removeEventListener("progress", progress);
|
|
148
|
+
xhr.removeEventListener("load", loaded);
|
|
149
|
+
xhr.removeEventListener("error", failed);
|
|
150
|
+
xhr.removeEventListener("abort", canceled);
|
|
151
|
+
xhr.removeEventListener("timeout", timedOut);
|
|
152
|
+
};
|
|
153
|
+
const finish = (error) => {
|
|
154
|
+
if (settled) return;
|
|
155
|
+
settled = true;
|
|
156
|
+
cleanup();
|
|
157
|
+
if (error !== void 0) reject(error);
|
|
158
|
+
else resolve();
|
|
159
|
+
};
|
|
160
|
+
const onAbort = () => {
|
|
161
|
+
finish(new ApiError("Request canceled.", "aborted"));
|
|
162
|
+
xhr.abort();
|
|
163
|
+
};
|
|
164
|
+
const progress = (event) => {
|
|
165
|
+
if (settled) return;
|
|
166
|
+
try {
|
|
167
|
+
check();
|
|
168
|
+
onProgress({ loaded: event.loaded, ...event.lengthComputable ? { total: event.total } : {} });
|
|
169
|
+
} catch (error) {
|
|
170
|
+
finish(error);
|
|
171
|
+
xhr.abort();
|
|
172
|
+
}
|
|
173
|
+
};
|
|
174
|
+
const loaded = () => {
|
|
175
|
+
if (settled) return;
|
|
176
|
+
try {
|
|
177
|
+
check();
|
|
178
|
+
if (xhr.status < 200 || xhr.status >= 300) {
|
|
179
|
+
throw new ApiError(`File upload failed (HTTP ${xhr.status}).`, "upload_failed", xhr.status);
|
|
180
|
+
}
|
|
181
|
+
finish();
|
|
182
|
+
} catch (error) {
|
|
183
|
+
finish(error);
|
|
184
|
+
}
|
|
185
|
+
};
|
|
186
|
+
const failed = () => finish(new ApiError("Unable to connect to the upload service.", "network_error"));
|
|
187
|
+
const canceled = () => finish(new ApiError("Request canceled.", "aborted"));
|
|
188
|
+
const timedOut = () => finish(new ApiError("Request timed out.", "timeout"));
|
|
189
|
+
try {
|
|
190
|
+
check();
|
|
191
|
+
xhr.open("PUT", url, true);
|
|
192
|
+
xhr.withCredentials = false;
|
|
193
|
+
xhr.setRequestHeader("Content-Type", contentType);
|
|
194
|
+
xhr.upload.addEventListener("progress", progress);
|
|
195
|
+
xhr.addEventListener("load", loaded);
|
|
196
|
+
xhr.addEventListener("error", failed);
|
|
197
|
+
xhr.addEventListener("abort", canceled);
|
|
198
|
+
xhr.addEventListener("timeout", timedOut);
|
|
199
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
200
|
+
check();
|
|
201
|
+
xhr.send(file);
|
|
202
|
+
} catch (error) {
|
|
203
|
+
finish(error);
|
|
204
|
+
}
|
|
205
|
+
});
|
|
206
|
+
}
|
|
207
|
+
function randomString(len = 32) {
|
|
208
|
+
const chars = "ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678";
|
|
209
|
+
let pwd = "";
|
|
210
|
+
for (let i = 0; i < len; i++) {
|
|
211
|
+
pwd += chars.charAt(Math.floor(Math.random() * chars.length));
|
|
212
|
+
}
|
|
213
|
+
return pwd;
|
|
214
|
+
}
|
|
215
|
+
function getFileType(file, fileName) {
|
|
216
|
+
const name = fileName || ("name" in file && typeof file.name === "string" ? file.name : "");
|
|
217
|
+
if (name) {
|
|
218
|
+
const dotIndex = name.lastIndexOf(".");
|
|
219
|
+
if (dotIndex !== -1) return name.slice(dotIndex + 1).toLowerCase();
|
|
220
|
+
}
|
|
221
|
+
const slashIndex = file.type.lastIndexOf("/");
|
|
222
|
+
return slashIndex !== -1 ? file.type.slice(slashIndex + 1).toLowerCase() : "";
|
|
223
|
+
}
|
|
136
224
|
function fileObjectName(file, fileName, productName) {
|
|
137
|
-
|
|
138
|
-
const name = fileName ?? ("name" in file && typeof file.name === "string" ? file.name : "");
|
|
139
|
-
const extension = ((_b = (_a = /\.([a-z0-9]{1,12})$/i.exec(name)) == null ? void 0 : _a[1]) == null ? void 0 : _b.toLowerCase()) ?? { "image/png": "png", "image/jpeg": "jpg", "image/webp": "webp", "image/gif": "gif", "application/pdf": "pdf", "video/mp4": "mp4", "audio/mpeg": "mp3" }[file.type] ?? "bin";
|
|
225
|
+
const extension = getFileType(file, fileName) || "bin";
|
|
140
226
|
const now = /* @__PURE__ */ new Date();
|
|
141
227
|
const day = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, "0")}-${String(now.getDate()).padStart(2, "0")}`;
|
|
142
|
-
return objectName(`temp_${productName}_${day}_${
|
|
228
|
+
return objectName(`temp_${productName}_${day}_${randomString(32)}.${extension}`);
|
|
143
229
|
}
|
|
144
230
|
function createUploadApi(getContext) {
|
|
145
231
|
return {
|
|
@@ -149,10 +235,11 @@ function createUploadApi(getContext) {
|
|
|
149
235
|
completeUpload: (params, options = {}) => withRequest(options, (signal) => complete(getContext(), params, signal)),
|
|
150
236
|
async uploadFile(params, options = {}) {
|
|
151
237
|
var _a;
|
|
152
|
-
if (!isObject(params) || !(params.file instanceof Blob) || !Number.isSafeInteger(params.file.size) || params.file.size <= 0 || params.file.size > maxFileSize || params.fileName !== void 0 && !isNonemptyString(params.fileName) || params.multipart !== void 0 && typeof params.multipart !== "boolean" || Object.keys(params).some((key2) => !["file", "fileName", "bucketName", "objectName", "multipart"].includes(key2))) {
|
|
238
|
+
if (!isObject(params) || !(params.file instanceof Blob) || !Number.isSafeInteger(params.file.size) || params.file.size <= 0 || params.file.size > maxFileSize || params.fileName !== void 0 && !isNonemptyString(params.fileName) || params.multipart !== void 0 && typeof params.multipart !== "boolean" || params.onUploadProgress !== void 0 && typeof params.onUploadProgress !== "function" || Object.keys(params).some((key2) => !["file", "fileName", "bucketName", "objectName", "multipart", "onUploadProgress"].includes(key2))) {
|
|
153
239
|
invalid("uploadFile requires a nonempty file within the R2 object size limit and valid upload parameters.");
|
|
154
240
|
}
|
|
155
241
|
const file = params.file;
|
|
242
|
+
const onUploadProgress = params.onUploadProgress;
|
|
156
243
|
const multipart = params.multipart === true || file.size >= multipartThreshold;
|
|
157
244
|
const context = getContext();
|
|
158
245
|
const key = params.objectName === void 0 ? fileObjectName(file, params.fileName, context.productName) : objectName(params.objectName);
|
|
@@ -168,10 +255,17 @@ function createUploadApi(getContext) {
|
|
|
168
255
|
};
|
|
169
256
|
return withRequest({ ...options, timeoutMs: options.timeoutMs ?? (multipart ? 30 * 6e4 : 12e4) }, async (signal) => {
|
|
170
257
|
check(signal);
|
|
171
|
-
|
|
172
|
-
const base = httpsUrl(signed.endpointBaseUrl, true).href.replace(/\/+$/, "");
|
|
173
|
-
check(signal);
|
|
258
|
+
let base;
|
|
174
259
|
const contentType = file.type || "application/octet-stream";
|
|
260
|
+
const progress = (value) => {
|
|
261
|
+
check(signal);
|
|
262
|
+
try {
|
|
263
|
+
onUploadProgress == null ? void 0 : onUploadProgress(value);
|
|
264
|
+
} catch {
|
|
265
|
+
throw new ApiError("Upload progress callback failed.", "upload_progress_failed");
|
|
266
|
+
}
|
|
267
|
+
check(signal);
|
|
268
|
+
};
|
|
175
269
|
const put = async (url, body) => {
|
|
176
270
|
check(signal);
|
|
177
271
|
const response = await fetch(url, {
|
|
@@ -189,7 +283,11 @@ function createUploadApi(getContext) {
|
|
|
189
283
|
if (multipart) {
|
|
190
284
|
const session = await initiate(context, { objectName: key, bucketName: bucket, contentType }, signal);
|
|
191
285
|
check(signal);
|
|
286
|
+
const publicBase = session.endpointBaseUrl === void 0 ? (await presign(context, { objectName: key, bucketName: bucket }, signal)).endpointBaseUrl : session.endpointBaseUrl;
|
|
287
|
+
check(signal);
|
|
288
|
+
base = httpsUrl(publicBase, true).href.replace(/\/+$/, "");
|
|
192
289
|
const partSize = Math.max(5 * MiB, Math.ceil(file.size / maxParts / MiB) * MiB);
|
|
290
|
+
const partCount = Math.ceil(file.size / partSize);
|
|
193
291
|
const parts = [];
|
|
194
292
|
for (let start = 0; start < file.size; start += partSize) {
|
|
195
293
|
check(signal);
|
|
@@ -201,12 +299,24 @@ function createUploadApi(getContext) {
|
|
|
201
299
|
throw new ApiError("R2 did not expose ETag. Configure the bucket CORS ExposeHeaders to include ETag.", "missing_etag", response.status);
|
|
202
300
|
}
|
|
203
301
|
parts.push({ ETag: etag, PartNumber: number });
|
|
302
|
+
progress({ loaded: parts.length, total: partCount });
|
|
204
303
|
}
|
|
205
304
|
check(signal);
|
|
206
|
-
await complete(context, { objectName: key, bucketName: bucket, uploadId: session.UploadId, parts }, signal);
|
|
305
|
+
const completed = await complete(context, { objectName: key, bucketName: bucket, uploadId: session.UploadId, parts }, signal);
|
|
207
306
|
check(signal);
|
|
307
|
+
if (completed.endpointBaseUrl !== void 0) {
|
|
308
|
+
base = httpsUrl(completed.endpointBaseUrl, true).href.replace(/\/+$/, "");
|
|
309
|
+
}
|
|
208
310
|
} else {
|
|
209
|
-
await
|
|
311
|
+
const signed = await presign(context, { objectName: key, bucketName: bucket }, signal);
|
|
312
|
+
base = httpsUrl(signed.endpointBaseUrl, true).href.replace(/\/+$/, "");
|
|
313
|
+
check(signal);
|
|
314
|
+
if (onUploadProgress) {
|
|
315
|
+
await putWithProgress(signed.url, file, contentType, signal, progress, () => check(signal));
|
|
316
|
+
check(signal);
|
|
317
|
+
} else {
|
|
318
|
+
await put(signed.url, file);
|
|
319
|
+
}
|
|
210
320
|
}
|
|
211
321
|
return { url: `${base}/${key.split("/").map(encodeURIComponent).join("/")}`, key, endpointBaseUrl: base };
|
|
212
322
|
});
|
package/dist/api/usage.js
CHANGED
|
@@ -8,13 +8,12 @@ const paths = {
|
|
|
8
8
|
};
|
|
9
9
|
function createUsageApi(getContext) {
|
|
10
10
|
const post = async (method, params, options = {}) => {
|
|
11
|
-
const digits = method === "addFreeUsageCnt" ? 1 : 2;
|
|
12
11
|
if (!isObject(params) || typeof params.cnt !== "number" || !Number.isFinite(params.cnt) || params.cnt <= 0 || Object.keys(params).some((key) => key !== "cnt")) {
|
|
13
12
|
invalid(`${method} requires a positive cnt number.`);
|
|
14
13
|
}
|
|
15
|
-
const
|
|
16
|
-
if (
|
|
17
|
-
invalid(`${method}
|
|
14
|
+
const maximumCnt = Number.MAX_SAFE_INTEGER / (method === "addFreeUsageCnt" ? 10 : 100);
|
|
15
|
+
if (params.cnt > maximumCnt) {
|
|
16
|
+
invalid(`${method} requires cnt within the safe numeric range.`);
|
|
18
17
|
}
|
|
19
18
|
return withRequest({ ...options, timeoutMs: options.timeoutMs ?? 3e4 }, async (signal) => {
|
|
20
19
|
var _a;
|