yichong-canva2 2.1.0 → 2.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 CHANGED
@@ -2,12 +2,16 @@
2
2
 
3
3
  使用一个 `YiChongCanvaProvider` 管理登录、订阅和额度,通过 `useYiChongCanva()` 直接调用后端接口。
4
4
 
5
+ `2.3.0` 新增 `client.createVtt` 和 `client.getVttStatus`,统一调用音视频转录接口,并沿用 Provider 身份、通用参数、超时与取消支持。
6
+
7
+ `2.2.0` 新增账户请求超时、有限重试与自动飞书告警,公开 `accountError` 供 Footer 展示失败及重试;上报切换到最新指定的 webhook。
8
+
5
9
  `2.1.0` 新增 `onUploadProgress` 和导出的 `UploadProgress` 类型,补齐视频目录参数,恢复消费数量原值透传,并将上传命名对齐旧随机算法与 MIME 后缀回退。上传继续复用 `ai.imgkits.com` 的四个 Cloudflare R2 接口,分片公开地址兼容旧响应,无需新增、迁移或部署后端接口。
6
10
 
7
11
  ## 使用
8
12
 
9
13
  ```sh
10
- npm install yichong-canva2@2.1.0
14
+ npm install yichong-canva2@2.3.0
11
15
  ```
12
16
 
13
17
  `1.2.0` 新增文本审核、三个消费接口,以及 Cloudflare R2 单次和分片上传;继续复用原有 Provider。
@@ -82,7 +86,7 @@ function GenerateButton() {
82
86
  }
83
87
  ```
84
88
 
85
- `baseUrl` 沿用原有账户扣费接口的地址。预测和文本审核请求默认使用 `https://api.imgkits.com`,可以通过可选的 `apiBaseUrl` 指定测试地址。
89
+ `baseUrl` 沿用原有账户扣费接口的地址。预测、文本审核和音视频转录请求默认使用 `https://api.imgkits.com`,可以通过可选的 `apiBaseUrl` 指定测试地址。
86
90
 
87
91
  文件签名服务默认使用 `https://ai.imgkits.com`,复用下表中的四个现有上传入口,可通过 Provider 的 `uploadBaseUrl` 指定测试服务。公开资源地址由后端响应的 `endpointBaseUrl` 提供:单次 PUT 使用普通签名响应;分片优先使用初始化响应,旧初始化响应缺少该字段时额外读取一次现有普通签名接口的地址信息,合并响应若提供最新地址则优先采用。`uploadBaseUrl` 是接口服务地址,不是公开资源地址。
88
92
 
@@ -101,6 +105,8 @@ function GenerateButton() {
101
105
  | `client.textCheck({ text, scene? })` | `POST /api/public/text-moderation/check` | `{ code: 0, msg: "展示文案", data: { allowed, decision, categories, ... } }` |
102
106
  | `client.contentExtract({ type, url })` | `POST {contentBaseUrl}/api/content-extract` | `{ code: 0, msg, data: { content: "提取的原文", ... } }` |
103
107
  | `client.chat({ payload, model?, img_url?, image_url?, image_urls? })` | `POST {chatBaseUrl}/api/chat` | `{ code: 0, msg, data: { result: "模型输出", ... } }` |
108
+ | `client.createVtt({ audio?, video?, ifRender?, email?, env? })` | `POST {apiBaseUrl}/get-vtt/create` | `{ code: 0, msg, data: { jobId, status, status_str, remark } }` |
109
+ | `client.getVttStatus({ jobId })` | `POST {apiBaseUrl}/get-vtt/status` | `{ code: 0, msg, data: { status, status_str, result, remark, final_video_url } }` |
104
110
  | `client.reportError({ error, source?, stage?, api?, context? })` | `POST https://report.imgkits.com` | Worker 原始 `{ success: true, data: { code: 0, ... } }` 或过滤响应 |
105
111
  | `client.reduceFreeCnt({ cnt })` | `POST {baseUrl}/api/user/reduce-free-cnt` | `{ ok: 0, msg: "success" }` |
106
112
  | `client.addMonthlyUsage({ cnt })` | `POST {baseUrl}/api/user/add-monthly-usage` | `{ ok: 0, msg: "success" }` |
@@ -434,6 +440,73 @@ try {
434
440
 
435
441
  默认超时 `360_000` 毫秒(6 分钟,包含读取响应正文),是客户端等待预算;后端模型回退可能花费更久,可通过第二参数的 `timeoutMs` 调整。`signal` 只取消客户端等待,不保证停止后端生成。失败沿用 `ApiError`,后端 `msg` 保留在 `error.message` / `error.userMessage`;上例直接展示该信息。内容提取与 chat 各自计算超时,共用取消信号。
436
442
 
443
+ ## 音视频转录
444
+
445
+ 继续使用原来的 `YiChongCanvaProvider`,子组件中直接调用 `client.createVtt()`、`client.getVttStatus()`。创建参数沿用后端的 `audio` / `video`;正文 `userId` 自动使用 Provider 的系统用户 ID(`profile.id`),不是 Canva 的 `userId`。JWT、渠道、平台 ID、语言和时区也由当前 Provider 注入。
446
+
447
+ ```tsx
448
+ import { useState } from 'react';
449
+ import { ApiError, useYiChongCanva } from 'yichong-canva2';
450
+
451
+ // 此组件放在现有 Provider 下。mediaUrl 应是上传后、服务端可访问的音频地址。
452
+ export function TranscriptionPanel({ mediaUrl }: { mediaUrl: string }) {
453
+ const client = useYiChongCanva();
454
+ const [jobId, setJobId] = useState('');
455
+ const [result, setResult] = useState('');
456
+ const [message, setMessage] = useState('');
457
+ const [busy, setBusy] = useState(false);
458
+
459
+ async function run(action: 'create' | 'status') {
460
+ setBusy(true);
461
+ setMessage('');
462
+ try {
463
+ if (action === 'create') {
464
+ setJobId('');
465
+ setResult('');
466
+ // 视频使用 { video: mediaUrl }。本地 File 先单独调用 client.uploadFile()。
467
+ const { data } = await client.createVtt({ audio: mediaUrl });
468
+ if (data.status === -1) throw new Error(data.remark || 'Transcription failed');
469
+ setJobId(data.jobId);
470
+ setMessage('Task ready. Check its status for subtitles.');
471
+ } else {
472
+ const { data } = await client.getVttStatus({ jobId });
473
+ if (data.status === -1) throw new Error(data.remark || 'Transcription failed');
474
+ if (data.status === 10) {
475
+ setResult(data.result ?? ''); // 字幕片段的 JSON 原文;需要数组时自行 JSON.parse。
476
+ setMessage('Completed');
477
+ } else {
478
+ setMessage('Transcription is still in progress.');
479
+ }
480
+ }
481
+ } catch (error) {
482
+ setMessage(error instanceof ApiError ? error.userMessage
483
+ : error instanceof Error ? error.message : 'Request failed');
484
+ } finally {
485
+ setBusy(false);
486
+ }
487
+ }
488
+
489
+ return <>
490
+ <button disabled={busy || !mediaUrl || client.loginStatus !== 'success'}
491
+ onClick={() => void run('create')}>Create transcription</button>
492
+ <button disabled={busy || !jobId || client.loginStatus !== 'success'}
493
+ onClick={() => void run('status')}>Check status</button>
494
+ <p>{message}</p>
495
+ <pre>{result}</pre>
496
+ </>;
497
+ }
498
+ ```
499
+
500
+ `data.result` 当前是字幕片段数组的 JSON 字符串,形如 `[{"start_time":"00:00:00.000","end_time":"00:00:01.500","text":"你好"}]`,并非 WEBVTT 文件文本。SDK 原样返回,字幕文件导出由应用另行处理。
501
+
502
+ 示例用手动查询展示两个原始接口,应用可以在业务流程里安排每 2–5 秒轮询,并设置总时限、在完成/失败/组件卸载时停止。SDK 本身只请求一次;任务状态 `0` 为排队、`2` 为处理中、`10` 为成功、`-1` 为失败。`code=0` 不代表转录已经成功。
503
+
504
+ 可选参数 `ifRender: 0 | 1`、`email`、`env` 原样传给后端;`env: 'pre'` 不立即派发,普通使用应省略。建议只传一个媒体地址,两者都非空时后端优先 `video`,允许另一个字段为空字符串。上传、轮询和消费不由这两个方法自动执行,后端原有用量处理保持不变。
505
+
506
+ 两个方法均默认超时 60 秒,可用第二参数 `{ timeoutMs, signal }` 覆盖或取消等待。取消请求不会取消后台任务,也不会自动重新创建。
507
+
508
+ 服务地址沿用 Provider 的 `apiBaseUrl`,默认 `https://api.imgkits.com`。这是客户端默认值,使用前需要后端部署 `/get-vtt/*` 并确认对应网关转发;这两个方法自 `2.3.0` 起提供。
509
+
437
510
  ## 文本审核
438
511
 
439
512
  `client.textCheck` 封装后端的公共文本审核接口,复用现有 Provider,无需另外配置令牌。请求发送到用户 JWT 公共入口。
@@ -471,9 +544,23 @@ const prediction = await client.getPrediction(
471
544
 
472
545
  取消只终止当前 HTTP 等待,不会取消已经创建的后端任务或撤销已提交的消费。创建、查询、文本审核和底层签名的默认请求超时为 60 秒,包含读取响应正文的时间;内容提取和大模型 `chat` 为 360 秒,消费为 30 秒,单次 PUT 上传为 120 秒,分片上传整体为 30 分钟。
473
546
 
547
+ ## 账户故障处理(2.2.0)
548
+
549
+ 继续使用一个 `YiChongCanvaProvider`,无需额外的上报 Provider 或 Footer 上报包装。账户模块会自动报告最终失败,业务 API 的错误仍在业务 catch 中按需显式调用 `client.reportError`。
550
+
551
+ - Canva token、身份验证、canvaid-login、passport 和 status 每步最多 10 秒(含响应正文)。首次登录及其重试共享 30 秒预算;`retry` 仍决定额外尝试次数,但不能突破总预算。
552
+ - 登录最终失败后 `loginStatus` 变为 `error`,Footer 停止圆圈并保留原 `Connect account` 重试按钮。`client.manualLogin()` 开始新一轮;取消旧请求和计时器,迟到响应不再更新状态。
553
+ - `client.refreshUserStatus()` 最多两次尝试,共享 30 秒;失败仍返回旧快照以兼容已有调用,同时设置 `client.accountError`。未登录时只返回当前快照,不抢占登录。返回快照不等于刷新成功,也不能据此认定消费成功。
554
+ - 支付轮询保留原快慢间隔和默认五分钟 TTL;连续三次网络/服务器故障提前结束,确定的响应/业务错误直接结束。健康的状态未变化、正常 TTL 或主动停止不告警;收尾补刷真实失败仍报告。补刷最多 10 秒并取消超时请求。
555
+ - `accountError` 为只读诊断快照或 `null`,包含 `operation`(login/refresh/poll)、`stage`、`code`、可用的 HTTP `status`、安全诊断 `message`、阶段尝试数 `attempts`、耗时 `elapsedMs` 和不带查询参数的 `api`。应用应根据状态显示本地化文案,不直接展示技术诊断。开始重试或成功后清除。
556
+ - Provider 按应用、接口、错误类型五分钟去重。自动报告不等待发送完成,发送失败不影响界面、不递归上报;卸载、主动取消、旧流程被替换都不告警。无需全局异常监听。
557
+ - 上报复用 `https://report.imgkits.com` 的现有转发协议,目标采用最新指定的 webhook,并携带应用/工具包版本。SDK 只收集必要的诊断字段,不发送 JWT、passport、查询参数或原始服务端正文。完全断网时不能保证告警送达。
558
+
559
+ 脚手架 Footer 只读取状态、展示新增失败提示和调用已有重试方法,不自行发送账户报告。正常七种额度文案、样式和布局保持原样。已有应用需要升级 SDK,并同步 Footer 的错误展示分支;更新脚手架不会自动改写旧应用。
560
+
474
561
  ## 错误上报
475
562
 
476
- 继续使用同一个 Provider,业务代码直接调用 `client.reportError`。`error` 接受 Error、ApiError、字符串或其他被抛出的值。Provider 自动补充产品渠道、应用 ID、应用版本及可用的用户 ID。工具包内置现有 Worker 地址和固定上报令牌,机器人固定为 `ROBOT_MONITOR`,应用无需新增配置或修改后端。
563
+ 继续使用同一个 Provider,业务代码直接调用 `client.reportError`。`error` 接受 Error、ApiError、字符串或其他被抛出的值。Provider 自动补充产品渠道、应用 ID、应用版本及可用的用户 ID。工具包内置现有 Worker 地址和固定上报令牌,通过 Worker 原有 `robot` 字段指定最新约定的飞书 webhook(业务应用无需再配置),应用无需新增配置或修改后端。
477
564
 
478
565
  固定令牌会随 npm 包和应用浏览器产物公开,不能视为保密凭据。此请求不向 Worker 发送用户 JWT 或 passport;这类值会从诊断正文中移除。上报可在 Provider 登录前调用,尚未获得的用户 ID 标为 unknown。
479
566
 
@@ -519,7 +606,7 @@ function GenerateButton() {
519
606
 
520
607
  `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 和处理阶段,避免传原始用户输入或文件。
521
608
 
522
- 成功原样返回 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 失败,由业务显式调用。
609
+ 成功原样返回 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 的失败仍由业务显式调用。
523
610
 
524
611
  默认超时 10 秒,支持第二参数 `{ signal, timeoutMs }`,只请求一次。沿用 Worker 的噪声过滤规则,本次不新增服务端限流或网关转发。上报失败不要再次上报自身异常;缺少 Provider 时抛出 provider_missing。`apiBaseUrl` 不影响上报地址,调用方不能覆盖机器人、地址或令牌。
525
612
 
@@ -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.3.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: "ROBOT_MONITOR", title: "Canva 应用错误", titleColor: "red", message });
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, {
@@ -5,7 +5,9 @@ const apiPaths = {
5
5
  getPrediction: "/replicate/getPrediction",
6
6
  textCheck: "/api/public/text-moderation/check",
7
7
  contentExtract: "/api/content-extract",
8
- chat: "/api/chat"
8
+ chat: "/api/chat",
9
+ createVtt: "/get-vtt/create",
10
+ getVttStatus: "/get-vtt/status"
9
11
  };
10
12
  function isObject(value) {
11
13
  return value !== null && typeof value === "object" && !Array.isArray(value);
@@ -99,8 +101,8 @@ async function postApi(context, method, params, options = {}) {
99
101
  Authorization: `Bearer ${userStatus.jwt}`,
100
102
  Channel: "ai"
101
103
  },
102
- // 创建任务还需在正文写入 user_id,始终以 Provider 账号为准。
103
- body: JSON.stringify(method === "createSpecifyPrediction" ? { ...params, user_id: uid } : params),
104
+ // 两种任务的后端字段不同;正文身份与 query 的 uid 始终使用同一账户快照。
105
+ body: JSON.stringify(method === "createSpecifyPrediction" ? { ...params, user_id: uid } : method === "createVtt" ? { ...params, userId: uid } : params),
104
106
  signal,
105
107
  credentials: "omit",
106
108
  redirect: "error"
@@ -0,0 +1,62 @@
1
+ import { ApiError } from "./error.js";
2
+ import { isObject, isNonemptyString, invalid, postApi } from "./request.js";
3
+ function validateMediaUrl(value) {
4
+ if (value === void 0 || value === "") return;
5
+ if (!isNonemptyString(value)) invalid("audio and video must be HTTP(S) URLs.");
6
+ let url;
7
+ try {
8
+ url = new URL(value);
9
+ } catch {
10
+ invalid("audio and video must be HTTP(S) URLs.");
11
+ }
12
+ if (!/^https?:\/\//i.test(value) || !["https:", "http:"].includes(url.protocol) || url.username || url.password) {
13
+ invalid("audio and video must be HTTP(S) URLs without credentials.");
14
+ }
15
+ }
16
+ function validateStatus(data) {
17
+ if (!isObject(data) || !Number.isInteger(data.status) || typeof data.status_str !== "string") {
18
+ throw new ApiError("Backend returned an invalid transcription status.", "invalid_response");
19
+ }
20
+ }
21
+ function createVttApi(getContext) {
22
+ return {
23
+ async createVtt(params, options) {
24
+ if (!isObject(params) || Object.keys(params).some((key) => !["audio", "video", "ifRender", "email", "env"].includes(key)) || !isNonemptyString(params.audio) && !isNonemptyString(params.video)) {
25
+ invalid("createVtt requires audio or video; userId is supplied by the current account.");
26
+ }
27
+ validateMediaUrl(params.audio);
28
+ validateMediaUrl(params.video);
29
+ if (params.ifRender !== void 0 && params.ifRender !== 0 && params.ifRender !== 1) {
30
+ invalid("ifRender must be 0 or 1.");
31
+ }
32
+ for (const key of ["email", "env"]) {
33
+ if (params[key] !== void 0 && typeof params[key] !== "string") invalid(`${key} must be a string.`);
34
+ }
35
+ const body = {};
36
+ for (const key of ["audio", "video", "ifRender", "email", "env"]) {
37
+ const value = params[key];
38
+ if (typeof value === "string" || typeof value === "number") body[key] = value;
39
+ }
40
+ const response = await postApi(getContext(), "createVtt", body, options);
41
+ validateStatus(response.data);
42
+ if (!isNonemptyString(response.data.jobId)) {
43
+ throw new ApiError("Backend returned an invalid transcription jobId.", "invalid_response");
44
+ }
45
+ return response;
46
+ },
47
+ async getVttStatus(params, options) {
48
+ if (!isObject(params) || !isNonemptyString(params.jobId) || Object.keys(params).some((key) => key !== "jobId")) {
49
+ invalid("getVttStatus requires a nonempty jobId.");
50
+ }
51
+ const response = await postApi(getContext(), "getVttStatus", { jobId: params.jobId }, options);
52
+ validateStatus(response.data);
53
+ if (response.data.result !== null && typeof response.data.result !== "string" || response.data.final_video_url !== null && typeof response.data.final_video_url !== "string") {
54
+ throw new ApiError("Backend returned an invalid transcription result.", "invalid_response");
55
+ }
56
+ return response;
57
+ }
58
+ };
59
+ }
60
+ export {
61
+ createVttApi
62
+ };
@@ -0,0 +1,69 @@
1
+ import { ApiError } from "../api/error.js";
2
+ import { throwIfAborted, withRequest } from "../api/transport.js";
3
+ class AccountRequestError extends ApiError {
4
+ constructor(message, code, stage, api) {
5
+ super(message, code, api == null ? void 0 : api.status);
6
+ this.stage = stage;
7
+ this.api = api;
8
+ this.name = "AccountRequestError";
9
+ }
10
+ }
11
+ async function accountStep(stage, options, work, api) {
12
+ var _a;
13
+ (_a = options.onStep) == null ? void 0 : _a.call(options, stage, api);
14
+ try {
15
+ return await withRequest({ signal: options.signal, timeoutMs: 1e4 }, work);
16
+ } catch (error) {
17
+ if (error instanceof AccountRequestError) throw error;
18
+ const code = error instanceof ApiError ? error.code : "network_error";
19
+ throw new AccountRequestError(code === "timeout" ? "Account request timed out." : "Account request failed.", code, stage, api);
20
+ }
21
+ }
22
+ function retryableAccountError(error) {
23
+ return error instanceof ApiError && (error.code === "timeout" || error.code === "network_error" || error.status === 408 || error.status === 429 || error.status != null && error.status >= 500);
24
+ }
25
+ function accountDelay(ms, signal) {
26
+ throwIfAborted(signal);
27
+ return new Promise((resolve, reject) => {
28
+ const cleanup = () => {
29
+ clearTimeout(timer);
30
+ signal.removeEventListener("abort", cancel);
31
+ };
32
+ const cancel = () => {
33
+ cleanup();
34
+ reject(new ApiError("Request canceled.", "aborted"));
35
+ };
36
+ const timer = setTimeout(() => {
37
+ cleanup();
38
+ resolve();
39
+ }, ms);
40
+ signal.addEventListener("abort", cancel, { once: true });
41
+ });
42
+ }
43
+ function createAccountReporter(report) {
44
+ const sent = /* @__PURE__ */ new Map();
45
+ return (error, appKey) => {
46
+ var _a;
47
+ if (error.code === "aborted") return;
48
+ const now = Date.now();
49
+ for (const [key2, time] of sent) if (now - time >= 3e5) sent.delete(key2);
50
+ const key = [appKey, ((_a = error.api) == null ? void 0 : _a.url) ?? error.stage, error.status, error.code].join("|");
51
+ if (sent.has(key)) return;
52
+ sent.set(key, now);
53
+ void report({
54
+ error: new ApiError(error.message, error.code, error.status),
55
+ source: error.stage === "canva_token" ? "host_sdk" : "api",
56
+ stage: `account.${error.operation}.${error.stage}`,
57
+ api: error.api,
58
+ context: { attempts: error.attempts, elapsed_ms: error.elapsedMs }
59
+ }).catch(() => {
60
+ });
61
+ };
62
+ }
63
+ export {
64
+ AccountRequestError,
65
+ accountDelay,
66
+ accountStep,
67
+ createAccountReporter,
68
+ retryableAccountError
69
+ };
@@ -28,6 +28,7 @@ const YiChongCanvaContext = React.createContext(
28
28
  updateCredits: () => {
29
29
  },
30
30
  loginStatus: "idle",
31
+ accountError: null,
31
32
  manualLogin: () => {
32
33
  },
33
34
  createSpecifyPrediction: async () => {
@@ -45,6 +46,12 @@ const YiChongCanvaContext = React.createContext(
45
46
  chat: async () => {
46
47
  throw new ApiError("Wrap your components in YiChongCanvaProvider first.", "provider_missing");
47
48
  },
49
+ createVtt: async () => {
50
+ throw new ApiError("Wrap your components in YiChongCanvaProvider first.", "provider_missing");
51
+ },
52
+ getVttStatus: async () => {
53
+ throw new ApiError("Wrap your components in YiChongCanvaProvider first.", "provider_missing");
54
+ },
48
55
  reportError: async () => {
49
56
  throw new ApiError("Wrap your components in YiChongCanvaProvider first.", "provider_missing");
50
57
  },
@@ -1,24 +1,26 @@
1
- import requestUrl from "./request.js";
1
+ import { accountRequest } from "./request.js";
2
+ import { isObject } from "../../../api/request.js";
3
+ import { throwIfAborted } from "../../../api/transport.js";
2
4
  const headers = {
3
5
  "Content-Type": "application/json"
4
6
  };
5
7
  const baseUrl = "https://usa.imgkits.com/";
6
- function getUserIds(token, appId, context) {
8
+ function getUserIds(token, appId, context, options = {}) {
7
9
  const queryString = new URLSearchParams({
8
10
  canva_user_token: token,
9
11
  appid: appId
10
12
  }).toString();
11
13
  const url = `https://canva.livepolls.app/getUserIdByAppid?${queryString}`;
12
- return requestUrl({
14
+ return accountRequest({
13
15
  url,
14
16
  method: "GET",
15
17
  headers,
16
18
  redirect: "follow"
17
- }, context);
19
+ }, context, "canva_identity", options, (body) => isObject(body.verified) && typeof body.verified.userId === "string" && !!body.verified.userId);
18
20
  }
19
- function handleUserLoginByCanvaId(userId, productName, context) {
21
+ function handleUserLoginByCanvaId(userId, productName, context, options = {}) {
20
22
  const url = baseUrl + productName + "/api/user/canvaid-login";
21
- return requestUrl({
23
+ return accountRequest({
22
24
  url,
23
25
  method: "POST",
24
26
  headers,
@@ -26,9 +28,10 @@ function handleUserLoginByCanvaId(userId, productName, context) {
26
28
  canva_id: userId
27
29
  }),
28
30
  redirect: "follow"
29
- }, context);
31
+ }, context, "canvaid_login", options, (body) => body.ok === 0 || body.code === 0 || body.success === true);
30
32
  }
31
- function getPassport(userId, productName, context) {
33
+ function getPassport(userId, productName, context, options = {}) {
34
+ if (options.signal) throwIfAborted(options.signal);
32
35
  const passport = localStorage.getItem(userId + "_passport");
33
36
  if (passport) {
34
37
  return Promise.resolve({
@@ -41,7 +44,7 @@ function getPassport(userId, productName, context) {
41
44
  if (productName === "imgkits") {
42
45
  url = baseUrl + "/api/user/canva-passport";
43
46
  }
44
- return requestUrl({
47
+ return accountRequest({
45
48
  url,
46
49
  method: "POST",
47
50
  headers,
@@ -49,23 +52,24 @@ function getPassport(userId, productName, context) {
49
52
  canva_id: userId
50
53
  }),
51
54
  redirect: "follow"
52
- }, context).then((res) => {
55
+ }, context, "canva_passport", options, (body) => isObject(body.data) && typeof body.data.passport === "string" && !!body.data.passport).then((res) => {
56
+ if (options.signal) throwIfAborted(options.signal);
53
57
  localStorage.setItem(userId + "_passport", res.data.passport);
54
58
  return res;
55
59
  });
56
60
  }
57
- function getUserStatusByPassport(passport, productName, context) {
61
+ function getUserStatusByPassport(passport, productName, context, options = {}) {
58
62
  const header = {
59
63
  "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
60
64
  "X-Access-Ticket": passport
61
65
  };
62
66
  const url = baseUrl + productName + "/api/user/status";
63
- return requestUrl({
67
+ return accountRequest({
64
68
  url,
65
69
  method: "POST",
66
70
  headers: header,
67
71
  redirect: "follow"
68
- }, context);
72
+ }, context, "status", options, (body) => isObject(body.data));
69
73
  }
70
74
  const apis = {
71
75
  getUserIds,
@@ -1,5 +1,33 @@
1
- import { addContextQuery, language } from "../../../api/request.js";
2
- const requestUrl = (option, context) => {
1
+ import { addContextQuery, language, isObject } from "../../../api/request.js";
2
+ import { accountStep, AccountRequestError } from "../../account.js";
3
+ function accountRequest(option, context, stage, options = {}, validate) {
4
+ const { url, ...init } = option;
5
+ const target = new URL(url);
6
+ const api = { url: target.origin + target.pathname, method: init.method ?? "GET" };
7
+ addContextQuery(target, context);
8
+ const headers = new Headers(init.headers);
9
+ headers.set("Accept-Language", language(context.getLocale));
10
+ return accountStep(stage, options, async (signal) => {
11
+ const response = await fetch(target.toString(), { ...init, headers, signal });
12
+ const metadata = { ...api, status: response.status, request_id: response.headers.get("x-request-id") ?? void 0 };
13
+ if (!response.ok) throw new AccountRequestError("Account service returned an HTTP error.", "http_error", stage, metadata);
14
+ let body;
15
+ try {
16
+ body = await response.json();
17
+ } catch {
18
+ throw new AccountRequestError("Account service returned invalid JSON.", "invalid_response", stage, metadata);
19
+ }
20
+ if (!isObject(body)) throw new AccountRequestError("Account service returned invalid data.", "invalid_response", stage, metadata);
21
+ const failedCode = [body.ok, body.code].find((value) => value !== void 0 && value !== 0 && value !== "0");
22
+ if (body.success === false || failedCode !== void 0) {
23
+ const code = typeof failedCode === "string" || typeof failedCode === "number" ? failedCode : "account_rejected";
24
+ throw new AccountRequestError("Account service rejected the request.", code, stage, { ...metadata, response_code: code });
25
+ }
26
+ if (validate && !validate(body)) throw new AccountRequestError("Account service returned incomplete data.", "invalid_response", stage, metadata);
27
+ return body;
28
+ }, api);
29
+ }
30
+ function requestUrl(option, context) {
3
31
  const { url, ...init } = option;
4
32
  const target = new URL(url);
5
33
  if (context) {
@@ -8,8 +36,9 @@ const requestUrl = (option, context) => {
8
36
  headers.set("Accept-Language", language(context.getLocale));
9
37
  init.headers = headers;
10
38
  }
11
- return fetch(target.toString(), init).then((res) => res.json());
12
- };
39
+ return fetch(target.toString(), init).then((response) => response.json());
40
+ }
13
41
  export {
42
+ accountRequest,
14
43
  requestUrl as default
15
44
  };