yichong-canva2 2.6.0 → 2.8.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,6 +2,12 @@
2
2
 
3
3
  使用一个 `YiChongCanvaProvider` 管理登录、订阅和额度,通过 `useYiChongCanva()` 直接调用后端接口。
4
4
 
5
+ **2.8.0(2026-12-04)**:适配 Canva 安全审核规范,登录身份验证请求 `getUserIdByAppid` 由原来的 `GET` + URL query 传递 `canva_user_token` 改为 `POST` + `Authorization: Bearer <token>` 请求头与 JSON body `{ appid }`,避免 Canva user JWT 出现在 URL 查询参数中。另外新通道新增 `payload`(**默认开启**):SDK 自动记下生成类接口的请求参数和结果,填到 `generate_success` / `generate_fail` 上,应用不用改代码;也可以给任何事件手动传。后台「Canva 行为统计」的事件详情直接可见,见下文「请求原文 payload(2.8.0 起,默认开启)」。**需要采集 Worker 先部署支持 payload 的版本**,否则带 payload 的事件会被拒收。
6
+
7
+ **2.7.1(2026-11-09)**:TTS 任务失败不再只能靠应用自己猜原因。新增 `client.waitForTextToSpeech`(轮询到完成,`status=-1` 立即抛分类后的 `ApiError`)和纯函数 `classifyTextToSpeechFailure`,把失败归成 `quota_exceeded` / `content_policy_violation` / `tts_failed` 三类,额度不足可以直接给升级入口。`createTextToSpeech`、`getTextToSpeechResult` 与既有字段含义不变,见下文「语音合成 TTS」。
8
+
9
+ **2.7.0(2026-10-27)**:配合后端 msg 分级,新增 `getDisplayMessage`、`getBackendErrorCode`、`isPolicyBlocked`,`ApiError` 增加 `errorCode`、`traceId`、`displayable`;新通道按后端 `error_code` 推断错误码和是否预期内。已有字段含义不变。见下文「错误文案(2.7.0 起)」。另外新增 `client.pricingUnit`:计量单位按渠道和界面语言从定价语言包读取,见「计量单位(2.7.0 起)」。
10
+
5
11
  **2.6.0**:新增行为与错误上报的**新通道**(schema `canva.v1`),**默认关闭**,升级后行为与 2.5.1 相同。开启后在旧 GET 统计、飞书错误上报之外额外发一份到 `telemetry.imgkits.com`;旧通道的请求内容、返回值和抛错行为不变。新增 `client.track`、`reportUsage` 的可选字段 `flow` / `timings` / `error`、`use()` 的可选第 4 个参数 `{ operationId }`,以及 `StageError`、`toErrorCode`、`createStageTimer`。见下文「新通道(2.6.0 起)」。
6
12
 
7
13
  **2.5.1**:只补类型、不改行为。`userStatus.profile` 增加后端 status 已返回的 `review?: boolean`(审核开关:true 审核期、false 正常运行、缺失为旧账户)、`canva_id?`、`created_at?`、`nextUsageResetTime?`。支付链接是否可点由应用按 `review === false || canAcceptPayments` 决定,SDK 不据此改变任何行为。
@@ -648,7 +654,25 @@ export function SpeechPanel() {
648
654
 
649
655
  创建返回任务 `jobId`;查询保留 `jobId/status/status_str/remark/result`。状态为 `0` 等待、`2` 处理中、`10` 完成、`-1` 失败。`code=0` 不是生成完成,创建本身也可能返回 `status=-1`,因此创建和查询均要检查任务状态。`result` 是音频 URL 字符串或 `null`,直接用于播放器或后续导入流程,无需 JSON.parse。
650
656
 
651
- 默认每次请求超时 60 秒,第二参数支持 `{ timeoutMs, signal }`。SDK 只发送一次请求,不自动重试、轮询、插入 Canva 或再扣一次额度;后端已有自己的 TTS 字符用量处理。需要轮询时,由业务设置总时限,并在完成、失败或组件卸载时停止。取消或超时只停止客户端等待,不保证后台任务取消或未扣费;尤其创建超时后不要直接重放创建请求。
657
+ 默认每次请求超时 60 秒,第二参数支持 `{ timeoutMs, signal }`。SDK 只发送一次请求,不自动重试、轮询、插入 Canva 或再扣一次额度;后端已有自己的 TTS 字符用量处理。需要轮询时用 `waitForTextToSpeech`,或由业务自己安排并设置总时限,在完成、失败或组件卸载时停止。取消或超时只停止客户端等待,不保证后台任务取消或未扣费;尤其创建超时后不要直接重放创建请求。
658
+
659
+ ### 等待任务并区分失败原因(2.7.1 起)
660
+
661
+ ```ts
662
+ import { classifyTextToSpeechFailure, getDisplayMessage } from "yichong-canva2";
663
+
664
+ const { data } = await client.waitForTextToSpeech({ jobId }, { signal });
665
+ const audioUrl = data.result;
666
+ // 抛错时按 code 选文案:额度不足给升级入口,内容违规用政策文案,其余用通用兜底。
667
+ // error.code: quota_exceeded | content_policy_violation | tts_failed | tts_timeout | aborted
668
+ ```
669
+
670
+ - `waitForTextToSpeech` 默认每 3 秒查一次、最多 50 次,整段等待预算 180 秒(`intervalMs` / `maxPolls` / `timeoutMs` 可覆盖);`status=10` 且有 `result` 才返回。
671
+ - `status=-1` 立即抛 `ApiError`,`code` 是分类结果,`errorCode` 同步写同一值(新通道按它分组),`status` 是任务状态(通常 `-1`)而不是 HTTP 状态。`displayable` 恒为 `false`:remark 原文不上屏,应用按 `code` 显示自己的翻译文案。
672
+ - 只重试连接失败和单次超时,连续 3 次即停;后端业务错误和 HTTP 错误直接抛出。轮询次数用完抛 `tts_timeout`,主动取消抛 `aborted`。
673
+ - `classifyTextToSpeechFailure(task)` 是纯函数,也可以直接用在创建响应上:优先任务上的 `error_code`(只认 `quota_exceeded`、`content_policy_violation`,其它取值归 `tts_failed`),没有再按 `remark` 关键字(现网已确认额度不足为 `User need to subscribe or purchase points`)。
674
+ - 创建接口仍原样返回 `status=-1` 的任务,不改成异常;应用在拿到创建响应后自行判断,或直接交给 `waitForTextToSpeech` 轮询。
675
+ - TTS 的 `remark` 取值仍缺后端的完整枚举(尤其内容违规),已知取值之外一律归 `tts_failed`,等后端补约定后再收敛关键字。
652
676
 
653
677
  ## 文本审核
654
678
 
@@ -687,6 +711,51 @@ const prediction = await client.getPrediction(
687
711
 
688
712
  取消只终止当前 HTTP 等待,不会取消已经创建的后端任务或撤销已提交的消费。创建、查询、文本审核和底层签名的默认请求超时为 60 秒,包含读取响应正文的时间;内容提取和大模型 `chat` 为 360 秒,消费为 30 秒,单次 PUT 上传为 120 秒,分片上传整体为 30 分钟。
689
713
 
714
+ ## 错误文案(2.7.0 起)
715
+
716
+ 后端对 `createSpecifyPrediction`、`getPrediction` 做了 msg 分级:失败时的 `msg`、任务的 `error_msg` / `error` 都是按 `Accept-Language` 翻译好的用户文案,原文挪到 `debug_msg` / `raw_*`(约定见仓库 `docs/前后端约定-错误文案msg分级.md`)。界面取文案只用 `getDisplayMessage`,取不到再显示应用自己的翻译文案:
717
+
718
+ ```ts
719
+ import { getDisplayMessage, isPolicyBlocked } from "yichong-canva2";
720
+
721
+ function describeFailure(error: unknown): string {
722
+ return getDisplayMessage(error) // 后端分级后的用户文案
723
+ || (isPolicyBlocked(error) ? policyText // 内容违规:换图 / 换样式
724
+ : fallbackText); // 应用自己的翻译兜底
725
+ }
726
+ ```
727
+
728
+ | 字段 / 函数 | 含义 |
729
+ | --- | --- |
730
+ | `ApiError.displayable` | message 能原样展示时为 true。创建失败看响应是否带 `debug_msg`,任务失败看任务是否带 `error_code`;其它接口、SDK 本地错误恒为 false |
731
+ | `ApiError.errorCode` | 后端 `error_code`(snake_case),逻辑判断只看它 |
732
+ | `ApiError.traceId` | 后端 `trace_id`(创建接口),新通道放进 `request_id` |
733
+ | `getDisplayMessage(error)` | 可展示的后端文案,没有返回 `""`;会顺着 `StageError` / `Error.cause` 找,最多 5 层 |
734
+ | `getBackendErrorCode(error)` | 后端 `error_code`,没有返回 `undefined` |
735
+ | `isPolicyBlocked(error)` | 后端判定内容违规(`content_policy_violation`),或 `StageError` 的 code 为 `POLICY_BLOCKED` |
736
+
737
+ - 不再需要维护「SDK 本地错误码清单」,也不要再用正则匹配 `E005`。
738
+ - 新通道:后端 `content_policy_violation` 记为 `POLICY_BLOCKED`(`generate_blocked`,不告警);`image_unavailable`、`invalid_input`、`too_many_concurrent_tasks`、`image_preprocessing_failed`、`no_output` 记为预期内。
739
+ - `code`、`userMessage` 含义不变:创建失败的 `code` 仍是后端数字 `1`,任务失败仍是 `prediction_failed`。
740
+ - 后端没打开分级时 `displayable` 一律为 false,应用显示自己的兜底文案。
741
+
742
+ ## 计量单位(2.7.0 起)
743
+
744
+ `client.pricingUnit` 是定价语言包里的计量单位,和定价页用同一份文件:改了定价单位,用户下次打开应用就生效,不用前端发版。
745
+
746
+ ```ts
747
+ const { pricingUnit } = useYiChongCanva();
748
+ // { unitNoun: "Quiz", unitNounPlural: "Quizze", locale: "de" },读取中或拿不到时为 null
749
+ const unitNoun = pricingUnit?.unitNoun ?? appConfig.unitConfig.unitNoun;
750
+ ```
751
+
752
+ - 地址:`https://project.deletetweets.ai/yichong_pricing_language/<productName>/<语言>.json` 的 `config.unit` / `config.plural_unit`。
753
+ - 语言:取界面语言的主语言(`zh-TW` → `zh`,`pt-BR` → `pt`),没有语言包再退到 `en`;换语言时重新读取,期间保留上一份单位,换渠道时旧单位作废。
754
+ - 每次打开都用 `cache: "no-cache"` 带 ETag 校验,没变时只回 304;单次 10 秒超时,不阻塞登录。
755
+ - 404、断网、超时、格式不对(非字符串、超过 40 字符、含 `<>{}`)都只得到 `null`,不抛错、不上报:部分渠道本来就没有定价语言包,应用退回 `config.ts` 的 `unitConfig`。
756
+ - 复数沿用「1 用单数,其余用复数」;语言包没有 `plural_unit` 时复数等于单数。
757
+ - 也导出了 `loadPricingUnit(productName, locale, signal?)`,供不用 Provider 的场景使用。
758
+
690
759
  ## 账户故障处理(2.2.0)
691
760
 
692
761
  继续使用一个 `YiChongCanvaProvider`,无需额外的上报 Provider 或 Footer 上报包装。账户模块会自动报告最终失败,业务 API 的错误仍在业务 catch 中按需显式调用 `client.reportError`。
@@ -868,3 +937,39 @@ client.track({ name: "quota_blocked", props: { cost: 2, state: "insufficient" }
868
937
  - `props` 只保留扁平的字符串、数字、布尔或 null,最多 20 个;键名命中 `prompt`、`text`、`url`、`token`、`file_name` 等敏感词,或值里含 URL、邮箱、JWT 时,整键丢弃。
869
938
  - `env`:页面运行在 localhost、测试模式(`updateTestMode`)或 `mode: "demo"` 时为 `dev`;审核期为 `review`;其余为 `production`。注意发布产物的 `NODE_ENV` 固定为 production,不能据此判断开发环境。
870
939
  - 发送:满 20 条或 5 秒发一批,页面隐藏和 Provider 卸载时用 `keepalive` 发送剩余事件;只对网络、超时、429、5xx 重试两次;服务端返回 503 或 `pause_seconds` 后本会话停止发送;每会话最多 500 条;同一错误 60 秒内合并为 `repeat_count`。不读写本地存储。
940
+
941
+ ### 请求原文 payload(2.8.0 起,默认开启)
942
+
943
+ `props` 只放统计属性,会丢掉提示词和 URL。`payload` 单独保存用户这次的请求原文和生成结果,后台「Canva 行为统计」事件详情的原始 JSON 里直接可见。
944
+
945
+ **默认自动采集,应用不用改代码。** 新通道打开(`telemetry.enabled: true`)后,SDK 记下这些接口的请求参数和最终结果:
946
+
947
+ | 请求 | 结果(只记终态,轮询中间状态不记) | 失败 |
948
+ |---|---|---|
949
+ | `createSpecifyPrediction`、`chat`、`createTextToSpeech`、`createVtt` 的参数 | `getPrediction` / `waitForPrediction`(succeeded / failed / canceled)、`chat` 的 `result`、TTS / VTT 状态 10 或 -1 的结果 | 以上接口抛错时的 `code` / `message` / `status` |
950
+
951
+ 应用上报 `generate_start` 时开始一次记录(按 `data.operation_id` 区分);上报 `generate_success` / `generate_fail` 且没传 `payload` 时,自动填上:
952
+
953
+ ```jsonc
954
+ "payload": {
955
+ "request": { "api": "createSpecifyPrediction", "params": { "owner": "…", "name": "…", "input": { "prompt": "…", "image_input": ["https://…"] } } },
956
+ "result": { "api": "waitForPrediction", "id": "…", "status": "succeeded", "output": ["https://…/out_0.png"] },
957
+ "error": { "api": "chat", "code": "http_error", "message": "…", "status": 429 } // 有失败时
958
+ }
959
+ ```
960
+
961
+ - `generate_start` 上报时请求还没发出,所以它本身不带自动 payload;请求参数出现在同一 `operation_id` 的 `generate_success` / `generate_fail` 上(后台「追踪」可以把整次操作串起来)。
962
+ - 每类最多保留最近 3 条,多于 1 条时为数组。同时进行多个生成时,接口调用记在最近一次 `generate_start` 的操作下。
963
+ - 应用自己传了 `payload` 时以应用的为准,不再自动填。也可以给任何事件手动传:
964
+
965
+ ```ts
966
+ void client.reportUsage({ sum_key: "generate_start", title: "Generation started",
967
+ data: { operation_id: operationId }, payload: { prompt, image_input: [imageUrl] } });
968
+ client.track({ name: "regenerate_click", operation_id: operationId, payload: { prompt } });
969
+ ```
970
+
971
+ - 关闭自动采集:`telemetry={{ enabled: true, payload: false }}`,此时只发应用手动传的 `payload`。新通道关闭或 `usageReporting.enabled: false` 时什么都不采集。
972
+ - 只进新通道,旧 GET 统计不带。包装只做记录,接口的参数、返回值和抛错不变。
973
+ - 保留提示词、http(s) 地址和普通参数。去掉:键名像凭据的值(`token`、`jwt`、`authorization`、`password`、`secret`、`apiKey` 等,整值换成 `[redacted]`)、已知登录凭据、JWT、`Bearer ...`;`data:` / `blob:` 地址只留类型(如 `[data-url image/png]`)。
974
+ - 只接受普通对象和数组:最多 7 层、100 个字段、数组 20 项;字符串先截到 2000 字符,序列化后超过 8 KB 时逐步缩短到 500、120 字符,仍超出则记为 `{ "_truncated": true }`。
975
+ - 服务端单独只保留 7 天(事件本身保留 30 天)。
package/dist/api/error.js CHANGED
@@ -3,7 +3,7 @@ class ApiError extends Error {
3
3
  * @param message 可展示的错误说明。
4
4
  * @param code 后端业务码或 SDK 标识,例如 invalid_request、timeout、network_error。
5
5
  * @param status 已取得的 HTTP 状态;请求发出前的错误等情况通常没有此值。
6
- * @param details 可选诊断数据和 Retry-After 秒数;仅提供信息,不触发重试。
6
+ * @param details 可选诊断数据、Retry-After 秒数和后端分级信息;仅提供信息,不触发重试。
7
7
  */
8
8
  constructor(message, code, status, details) {
9
9
  super(message);
@@ -13,12 +13,38 @@ class ApiError extends Error {
13
13
  this.userMessage = message;
14
14
  this.data = details == null ? void 0 : details.data;
15
15
  this.retryAfter = details == null ? void 0 : details.retryAfter;
16
+ this.errorCode = typeof (details == null ? void 0 : details.errorCode) === "string" && errorCodePattern.test(details.errorCode) ? details.errorCode : void 0;
17
+ this.traceId = typeof (details == null ? void 0 : details.traceId) === "string" && details.traceId.trim() ? details.traceId.trim().slice(0, 128) : void 0;
18
+ this.displayable = (details == null ? void 0 : details.displayable) === true && message.trim().length > 0;
16
19
  }
17
20
  }
21
+ const errorCodePattern = /^[a-z][a-z0-9_]{1,63}$/;
22
+ const MAX_CAUSE_DEPTH = 5;
23
+ function findInChain(error, pick) {
24
+ let current = error;
25
+ for (let depth = 0; depth <= MAX_CAUSE_DEPTH && current !== null && typeof current === "object"; depth++) {
26
+ const found = pick(current);
27
+ if (found !== void 0) return found;
28
+ current = current.cause;
29
+ }
30
+ return void 0;
31
+ }
32
+ function getDisplayMessage(error) {
33
+ return findInChain(error, (value) => value instanceof ApiError && value.displayable ? value.message.trim() : void 0) ?? "";
34
+ }
35
+ function getBackendErrorCode(error) {
36
+ return findInChain(error, (value) => value instanceof ApiError ? value.errorCode : void 0);
37
+ }
38
+ function isPolicyBlocked(error) {
39
+ return findInChain(error, (value) => value instanceof ApiError && value.errorCode === "content_policy_violation" || !(value instanceof ApiError) && value.code === "POLICY_BLOCKED" ? true : void 0) === true;
40
+ }
18
41
  function isAbortError(error) {
19
42
  return error instanceof ApiError ? error.code === "aborted" : error !== null && typeof error === "object" && "name" in error && error.name === "AbortError";
20
43
  }
21
44
  export {
22
45
  ApiError,
23
- isAbortError
46
+ getBackendErrorCode,
47
+ getDisplayMessage,
48
+ isAbortError,
49
+ isPolicyBlocked
24
50
  };
@@ -124,8 +124,13 @@ function createPredictionApi(getContext) {
124
124
  }
125
125
  if (task) {
126
126
  if (["failed", "canceled", "aborted"].includes(task.status)) {
127
- const message = [task.error_msg, task.error].find(isNonemptyString) || "Generation failed.";
128
- throw new ApiError(message, "prediction_failed", void 0, { data: { id: task.id, status: task.status } });
127
+ const message = [task.error_msg, task.error].find(isNonemptyString);
128
+ const errorCode = isNonemptyString(task.error_code) ? task.error_code : void 0;
129
+ throw new ApiError(message || "Generation failed.", "prediction_failed", void 0, {
130
+ data: { id: task.id, status: task.status, ...errorCode ? { error_code: errorCode } : {} },
131
+ errorCode,
132
+ displayable: errorCode !== void 0 && message !== void 0
133
+ });
129
134
  }
130
135
  if (task.status === "succeeded" || allowEarlyOutput && getPredictionOutputUrl(task.output)) return task;
131
136
  }
@@ -24,7 +24,7 @@ function createErrorReportingApi(getContext) {
24
24
  platform: "canva_addon",
25
25
  app_id: context.appId,
26
26
  app_version: String(context.version),
27
- sdk_version: "2.6.0",
27
+ sdk_version: "2.8.0",
28
28
  user_id: ((_d = context.userStatus.profile) == null ? void 0 : _d.id) ?? "unknown",
29
29
  platform_uid: context.userStatus.userId ?? "unknown",
30
30
  ...reportingPayload(params, secrets)
@@ -77,15 +77,20 @@ async function readJson(response) {
77
77
  throw new ApiError("Backend returned an invalid JSON response.", response.ok ? "invalid_response" : "http_error", response.status);
78
78
  }
79
79
  }
80
- function backendError(response, payload, fallbackCode) {
81
- const message = isObject(payload) && isNonemptyString(payload.msg) ? payload.msg : isObject(payload) && isNonemptyString(payload.message) ? payload.message : "Backend request failed.";
80
+ function backendError(response, payload, fallbackCode, options = {}) {
81
+ const hasMsg = isObject(payload) && isNonemptyString(payload.msg);
82
+ const message = hasMsg ? payload.msg : isObject(payload) && isNonemptyString(payload.message) ? payload.message : "Backend request failed.";
82
83
  const code = isObject(payload) && (typeof payload.code === "string" || typeof payload.code === "number") ? payload.code : fallbackCode;
83
84
  const retryAfter = response.headers.get("Retry-After");
84
85
  return new ApiError(message, code, response.status, {
85
86
  data: isObject(payload) && isObject(payload.data) ? payload.data : void 0,
86
- retryAfter: retryAfter !== null && /^\d+$/.test(retryAfter) && Number.isSafeInteger(Number(retryAfter)) ? Number(retryAfter) : void 0
87
+ retryAfter: retryAfter !== null && /^\d+$/.test(retryAfter) && Number.isSafeInteger(Number(retryAfter)) ? Number(retryAfter) : void 0,
88
+ errorCode: isObject(payload) ? payload.error_code : void 0,
89
+ traceId: isObject(payload) ? payload.trace_id : void 0,
90
+ displayable: options.tiered === true && hasMsg && isObject(payload) && typeof payload.debug_msg === "string"
87
91
  });
88
92
  }
93
+ const tieredMethods = /* @__PURE__ */ new Set(["createSpecifyPrediction"]);
89
94
  async function postApi(context, method, params, options = {}) {
90
95
  return withRequest(options, async (signal) => {
91
96
  var _a;
@@ -114,14 +119,15 @@ async function postApi(context, method, params, options = {}) {
114
119
  redirect: "error"
115
120
  });
116
121
  const payload = await readJson(response);
117
- if (!response.ok) throw backendError(response, payload, "http_error");
122
+ const tiered = tieredMethods.has(method);
123
+ if (!response.ok) throw backendError(response, payload, "http_error", { tiered });
118
124
  if (method === "cancelPrediction" && isObject(payload) && payload.code === void 0) {
119
125
  return payload;
120
126
  }
121
127
  if (!isObject(payload) || typeof payload.code !== "number" && typeof payload.code !== "string") {
122
128
  throw new ApiError("Backend returned an invalid response envelope.", "invalid_response", response.status);
123
129
  }
124
- if (payload.code !== 0) throw backendError(response, payload, "http_error");
130
+ if (payload.code !== 0) throw backendError(response, payload, "http_error", { tiered });
125
131
  if (typeof payload.msg !== "string" || !Object.prototype.hasOwnProperty.call(payload, "data")) {
126
132
  throw new ApiError("Backend returned an invalid response envelope.", "invalid_response", response.status);
127
133
  }
@@ -1,4 +1,4 @@
1
- import { cleanProps, cleanTimings, cleanDuration, cleanError } from "./sanitize.js";
1
+ import { cleanProps, cleanTimings, cleanDuration, cleanError, cleanPayload } from "./sanitize.js";
2
2
  const DEFAULT_TELEMETRY_ENDPOINT = "https://telemetry.imgkits.com/v1/events";
3
3
  const namePattern = /^[a-z][a-z0-9_]{1,47}$/;
4
4
  const idPattern = /^[A-Za-z0-9_.:-]{1,128}$/;
@@ -115,7 +115,7 @@ function createTelemetry(getContext) {
115
115
  event_id: newId(),
116
116
  occurred_at: (/* @__PURE__ */ new Date()).toISOString(),
117
117
  seq: ++seq,
118
- app: { id: context.appId, channel: context.productName, version: String(context.version), sdk: "2.6.0" },
118
+ app: { id: context.appId, channel: context.productName, version: String(context.version), sdk: "2.8.0" },
119
119
  user: { id: context.userId && idPattern.test(context.userId) ? context.userId : null, plan: context.plan },
120
120
  session: { id: context.sessionId, locale: context.locale },
121
121
  env,
@@ -132,6 +132,8 @@ function createTelemetry(getContext) {
132
132
  const duration = cleanDuration(params.duration_ms);
133
133
  if (duration !== void 0) event.duration_ms = duration;
134
134
  if (params.error) event.error = cleanError(params.error, context.secrets);
135
+ const payload = cleanPayload(params.payload, context.secrets);
136
+ if (payload) event.payload = payload;
135
137
  return event;
136
138
  };
137
139
  const capture = (mapped) => {
@@ -35,7 +35,8 @@ function mapUsage(params) {
35
35
  props: data,
36
36
  timings: params.timings,
37
37
  duration_ms: typeof duration_ms === "number" ? duration_ms : void 0,
38
- error
38
+ error,
39
+ payload: params.payload
39
40
  },
40
41
  envOverride
41
42
  };
@@ -0,0 +1,131 @@
1
+ import { ApiError } from "../error.js";
2
+ const MAX_ENTRIES = 3;
3
+ const MAX_SLOTS = 10;
4
+ function createPayloadRecorder() {
5
+ const slots = /* @__PURE__ */ new Map();
6
+ let current = "";
7
+ const slot = (key) => {
8
+ let value = slots.get(key);
9
+ if (!value) {
10
+ value = { request: [], result: [], error: [] };
11
+ slots.set(key, value);
12
+ while (slots.size > MAX_SLOTS) slots.delete(slots.keys().next().value);
13
+ }
14
+ return value;
15
+ };
16
+ return {
17
+ begin(operationId) {
18
+ try {
19
+ current = typeof operationId === "string" ? operationId : "";
20
+ slots.delete(current);
21
+ slot(current);
22
+ } catch {
23
+ }
24
+ },
25
+ record(kind, api, value) {
26
+ try {
27
+ const list = slot(current)[kind];
28
+ list.push({ api, ...value });
29
+ if (list.length > MAX_ENTRIES) list.shift();
30
+ } catch {
31
+ }
32
+ },
33
+ take(operationId) {
34
+ try {
35
+ const key = typeof operationId === "string" && slots.has(operationId) ? operationId : slots.has("") ? "" : void 0;
36
+ if (key === void 0) return void 0;
37
+ const value = slots.get(key);
38
+ slots.delete(key);
39
+ if (current === key) current = "";
40
+ const payload = {};
41
+ for (const kind of ["request", "result", "error"]) {
42
+ const list = value[kind];
43
+ if (list.length) payload[kind] = list.length === 1 ? list[0] : list;
44
+ }
45
+ return Object.keys(payload).length ? payload : void 0;
46
+ } catch {
47
+ return void 0;
48
+ }
49
+ }
50
+ };
51
+ }
52
+ const dataOf = (response) => {
53
+ if (!response || typeof response !== "object") return void 0;
54
+ const value = response;
55
+ return value.code !== void 0 && value.data && typeof value.data === "object" ? value.data : value;
56
+ };
57
+ const pick = (source, keys) => {
58
+ if (!source) return void 0;
59
+ const output = {};
60
+ for (const key of keys) if (source[key] !== void 0 && source[key] !== null && source[key] !== "") output[key] = source[key];
61
+ return output;
62
+ };
63
+ const asParams = (params) => params && typeof params === "object" && !Array.isArray(params) ? { params } : void 0;
64
+ const predictionResult = (response) => {
65
+ const task = dataOf(response);
66
+ if (!task || !["succeeded", "failed", "canceled", "aborted"].includes(String(task.status))) return void 0;
67
+ return pick(task, ["id", "status", "output", "error", "error_msg", "error_code", "raw_error", "raw_error_msg"]);
68
+ };
69
+ const taskResult = (keys) => (response) => {
70
+ const task = dataOf(response);
71
+ if (!task || task.status !== 10 && task.status !== -1) return void 0;
72
+ return pick(task, ["status", "status_str", "remark", ...keys]);
73
+ };
74
+ const RECORD_SPECS = {
75
+ createSpecifyPrediction: { request: asParams },
76
+ getPrediction: { result: predictionResult },
77
+ waitForPrediction: { result: predictionResult },
78
+ chat: { request: asParams, result: (response) => pick(dataOf(response), ["result"]) },
79
+ createTextToSpeech: { request: asParams },
80
+ getTextToSpeechResult: { result: taskResult(["jobId", "result"]) },
81
+ waitForTextToSpeech: { result: taskResult(["jobId", "result"]) },
82
+ createVtt: { request: asParams },
83
+ getVttStatus: { result: taskResult(["result", "final_video_url"]) }
84
+ };
85
+ function errorEntry(error) {
86
+ if (error instanceof ApiError) return pick(error, ["code", "message", "status", "errorCode", "traceId"]) ?? {};
87
+ if (error instanceof Error) return { name: error.name, message: error.message };
88
+ return { message: String(error) };
89
+ }
90
+ function recordApi(api, recorder, enabled, specs = RECORD_SPECS) {
91
+ const wrapped = { ...api };
92
+ for (const [name, spec] of Object.entries(specs)) {
93
+ const original = api[name];
94
+ if (typeof original !== "function") continue;
95
+ wrapped[name] = function(...args) {
96
+ let on = false;
97
+ try {
98
+ on = enabled();
99
+ if (on && spec.request) {
100
+ const entry = spec.request(args[0]);
101
+ if (entry) recorder.record("request", name, entry);
102
+ }
103
+ } catch {
104
+ }
105
+ const promise = original.apply(api, args);
106
+ if (!on) return promise;
107
+ return promise.then((response) => {
108
+ try {
109
+ if (spec.result) {
110
+ const entry = spec.result(response);
111
+ if (entry) recorder.record("result", name, entry);
112
+ }
113
+ } catch {
114
+ }
115
+ return response;
116
+ }, (error) => {
117
+ try {
118
+ recorder.record("error", name, errorEntry(error));
119
+ } catch {
120
+ }
121
+ throw error;
122
+ });
123
+ };
124
+ }
125
+ return wrapped;
126
+ }
127
+ export {
128
+ RECORD_SPECS,
129
+ createPayloadRecorder,
130
+ recordApi
131
+ };
@@ -64,7 +64,18 @@ function cleanTimings(input) {
64
64
  function cleanDuration(value) {
65
65
  return typeof value === "number" && Number.isFinite(value) && value >= 0 && value <= MAX_DURATION ? Math.round(value) : void 0;
66
66
  }
67
- const expectedCodes = /* @__PURE__ */ new Set(["ABORTED", "POLICY_BLOCKED", "NOT_FOUND", "USER_OFFLINE", "PERMISSION_DENIED"]);
67
+ const expectedCodes = /* @__PURE__ */ new Set([
68
+ "ABORTED",
69
+ "POLICY_BLOCKED",
70
+ "NOT_FOUND",
71
+ "USER_OFFLINE",
72
+ "PERMISSION_DENIED",
73
+ "IMAGE_UNAVAILABLE",
74
+ "INVALID_INPUT",
75
+ "TOO_MANY_CONCURRENT_TASKS",
76
+ "IMAGE_PREPROCESSING_FAILED",
77
+ "NO_OUTPUT"
78
+ ]);
68
79
  function cleanError(input, secrets) {
69
80
  var _a;
70
81
  const stage = isReportStage(input.stage) ? input.stage : "unknown";
@@ -83,14 +94,73 @@ function cleanError(input, secrets) {
83
94
  if (cause instanceof ApiError) {
84
95
  if (cause.status !== void 0) payload.http_status = cause.status;
85
96
  if (typeof cause.code === "number") payload.backend_code = String(cause.code);
86
- const requestId = (_a = cause.data) == null ? void 0 : _a.request_id;
97
+ const requestId = cause.traceId ?? ((_a = cause.data) == null ? void 0 : _a.request_id);
87
98
  if (typeof requestId === "string") payload.request_id = usageReportingText(requestId, 128, secrets);
88
99
  }
89
100
  return payload;
90
101
  }
102
+ const MAX_PAYLOAD_BYTES = 8 * 1024;
103
+ const credentialKey = /(?:token|jwt|passport|authorization|cookie|password|secret|credential|apikey|accesskey|privatekey|signature)/;
104
+ const STRING_LIMITS = [2e3, 500, 120];
105
+ function payloadText(value, max, secrets) {
106
+ let clean = value;
107
+ for (const secret of secrets) {
108
+ if (typeof secret === "string" && secret.length >= 4) clean = clean.split(secret).join("[redacted]");
109
+ }
110
+ clean = clean.replace(/\bdata:([a-z0-9.+-]+\/[a-z0-9.+-]+)?[;,][^\s"']*/gi, (_, mime) => `[data-url${mime ? ` ${mime}` : ""}]`).replace(/\bblob:[^\s"']+/gi, "[blob-url]").replace(/\bBearer\s+\S+/gi, "Bearer [redacted]").replace(/\beyJ[A-Za-z0-9_-]*\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/g, "[redacted]").replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/g, "");
111
+ const chars = Array.from(clean);
112
+ return chars.length > max ? `${chars.slice(0, max).join("")}…[+${chars.length - max}]` : clean;
113
+ }
114
+ function payloadCopy(input, maxString, secrets) {
115
+ let fields = 0;
116
+ const seen = /* @__PURE__ */ new Set();
117
+ const walk = (value, depth) => {
118
+ if (value === null || typeof value === "boolean") return value;
119
+ if (typeof value === "number") return Number.isFinite(value) ? value : null;
120
+ if (typeof value === "string") return payloadText(value, maxString, secrets);
121
+ if (typeof value !== "object" || seen.has(value) || depth > 6) return void 0;
122
+ if (!Array.isArray(value) && Object.getPrototypeOf(value) !== Object.prototype && Object.getPrototypeOf(value) !== null) return void 0;
123
+ seen.add(value);
124
+ try {
125
+ const descriptors = Object.entries(Object.getOwnPropertyDescriptors(value)).filter(([key, d]) => d.enumerable && "value" in d && (!Array.isArray(value) || /^\d+$/.test(key)));
126
+ if (Array.isArray(value)) {
127
+ const items = descriptors.slice(0, 20).map(([, d]) => walk(d.value, depth + 1)).filter((item) => item !== void 0);
128
+ if (descriptors.length > 20) items.push(`…[+${descriptors.length - 20}]`);
129
+ return items;
130
+ }
131
+ const output = {};
132
+ for (const [key, d] of descriptors) {
133
+ if (++fields > 100 || key.length > 64) continue;
134
+ if (credentialKey.test(key.toLowerCase().replace(/[^a-z]/g, ""))) {
135
+ output[key] = "[redacted]";
136
+ continue;
137
+ }
138
+ const child = walk(d.value, depth + 1);
139
+ if (child !== void 0) output[key] = child;
140
+ }
141
+ return output;
142
+ } finally {
143
+ seen.delete(value);
144
+ }
145
+ };
146
+ return walk(input, 0);
147
+ }
148
+ function cleanPayload(input, secrets) {
149
+ if (input === null || typeof input !== "object" || Array.isArray(input)) return void 0;
150
+ const encoder = new TextEncoder();
151
+ for (const limit of STRING_LIMITS) {
152
+ const copy = payloadCopy(input, limit, secrets);
153
+ if (!copy || typeof copy !== "object" || Array.isArray(copy)) return void 0;
154
+ if (!Object.keys(copy).length) return void 0;
155
+ if (encoder.encode(JSON.stringify(copy)).length <= MAX_PAYLOAD_BYTES) return copy;
156
+ }
157
+ return { _truncated: true };
158
+ }
91
159
  export {
160
+ MAX_PAYLOAD_BYTES,
92
161
  cleanDuration,
93
162
  cleanError,
163
+ cleanPayload,
94
164
  cleanProps,
95
165
  cleanTimings,
96
166
  isSensitiveKey
@@ -38,6 +38,9 @@ class StageError extends Error {
38
38
  function toErrorCode(error, stage) {
39
39
  if (error instanceof StageError) return error.code;
40
40
  if (isAbortError(error)) return "ABORTED";
41
+ if (error instanceof ApiError && error.errorCode) {
42
+ return error.errorCode === "content_policy_violation" ? "POLICY_BLOCKED" : error.errorCode.toUpperCase();
43
+ }
41
44
  const code = error instanceof ApiError ? error.code : error !== null && typeof error === "object" && "code" in error ? error.code : void 0;
42
45
  if (typeof code === "string" && /^[a-z][a-z0-9_]{1,63}$/.test(code)) return code.toUpperCase();
43
46
  if (typeof code === "string" && errorCodePattern.test(code)) return code;
package/dist/api/tts.js CHANGED
@@ -1,5 +1,6 @@
1
1
  import { ApiError } from "./error.js";
2
2
  import { isObject, isNonemptyString, invalid, postApi, validateJson } from "./request.js";
3
+ import { waitForTextToSpeech } from "./tts_task.js";
3
4
  const createKeys = ["text", "voice", "emotion", "speed", "language", "refer_audio", "refer_audio_text"];
4
5
  function validateTextLength(text, field) {
5
6
  if ([...text].length > 5e3) invalid(`${field} must not exceed 5000 characters.`);
@@ -23,7 +24,7 @@ function validateTask(data) {
23
24
  }
24
25
  }
25
26
  function createTextToSpeechApi(getContext) {
26
- return {
27
+ const api = {
27
28
  async createTextToSpeech(params, options) {
28
29
  if (!isObject(params) || !isNonemptyString(params.text) || Object.keys(params).some((key) => !createKeys.includes(key))) {
29
30
  invalid("createTextToSpeech requires text; account identity and billing fields cannot be overridden.");
@@ -57,8 +58,13 @@ function createTextToSpeechApi(getContext) {
57
58
  throw new ApiError("Backend returned an invalid text-to-speech result.", "invalid_response");
58
59
  }
59
60
  return response;
61
+ },
62
+ // 轮询实现放在 tts_task.ts:与本文件其余方法一样挂在 client 上,便于应用只调一个方法。
63
+ waitForTextToSpeech(params, options) {
64
+ return waitForTextToSpeech(api, params, options);
60
65
  }
61
66
  };
67
+ return api;
62
68
  }
63
69
  export {
64
70
  createTextToSpeechApi
@@ -0,0 +1,107 @@
1
+ import { ApiError } from "./error.js";
2
+ import { isObject, isNonemptyString, invalid } from "./request.js";
3
+ import { withRequest, throwIfAborted } from "./transport.js";
4
+ const TTS_POLL_INTERVAL_MS = 3e3;
5
+ const TTS_MAX_POLLS = 50;
6
+ const TTS_WAIT_TIMEOUT_MS = 18e4;
7
+ const ERROR_CODE_KINDS = {
8
+ quota_exceeded: "quota_exceeded",
9
+ content_policy_violation: "content_policy_violation"
10
+ };
11
+ const QUOTA_REMARK_PATTERNS = [
12
+ /subscribe/i,
13
+ /purchase\s+points/i,
14
+ /(insufficient|not\s+enough|no)\s+(balance|credit|point|quota)/i,
15
+ /\bquota\b/i,
16
+ /\bbalance\b/i
17
+ ];
18
+ const POLICY_REMARK_PATTERNS = [
19
+ /polic(y|ies)/i,
20
+ /\bsafety\b/i,
21
+ /\bsensitive\b/i,
22
+ /\bflagged\b/i,
23
+ /\b(nsfw|inappropriate|prohibited|violat)/i
24
+ ];
25
+ function classifyTextToSpeechFailure(task) {
26
+ if (!isObject(task)) return { code: "tts_failed" };
27
+ const errorCode = typeof task.error_code === "string" ? task.error_code.trim().toLowerCase() : "";
28
+ if (errorCode) {
29
+ return { code: ERROR_CODE_KINDS[errorCode] ?? "tts_failed" };
30
+ }
31
+ const remark = typeof task.remark === "string" ? task.remark : "";
32
+ if (QUOTA_REMARK_PATTERNS.some((pattern) => pattern.test(remark))) return { code: "quota_exceeded" };
33
+ if (POLICY_REMARK_PATTERNS.some((pattern) => pattern.test(remark))) return { code: "content_policy_violation" };
34
+ return { code: "tts_failed" };
35
+ }
36
+ const FAILURE_MESSAGES = {
37
+ quota_exceeded: "The text-to-speech task failed: not enough balance.",
38
+ content_policy_violation: "The text-to-speech task failed: the text was blocked.",
39
+ tts_failed: "The text-to-speech task failed."
40
+ };
41
+ function taskFailure(task) {
42
+ const { code } = classifyTextToSpeechFailure(task);
43
+ return new ApiError(FAILURE_MESSAGES[code], code, task.status, { errorCode: code });
44
+ }
45
+ function timeoutFailure() {
46
+ return new ApiError("Waiting for the text-to-speech task timed out.", "tts_timeout");
47
+ }
48
+ function delay(milliseconds, signal) {
49
+ throwIfAborted(signal);
50
+ return new Promise((resolve, reject) => {
51
+ const cancel = () => {
52
+ clearTimeout(timer);
53
+ signal.removeEventListener("abort", cancel);
54
+ reject(new ApiError("Request canceled.", "aborted"));
55
+ };
56
+ const timer = setTimeout(() => {
57
+ signal.removeEventListener("abort", cancel);
58
+ resolve();
59
+ }, milliseconds);
60
+ signal.addEventListener("abort", cancel, { once: true });
61
+ if (signal.aborted) cancel();
62
+ });
63
+ }
64
+ async function waitForTextToSpeech(api, params, options = {}) {
65
+ if (!isObject(params) || !isNonemptyString(params.jobId) || Object.keys(params).some((key) => key !== "jobId")) {
66
+ invalid("waitForTextToSpeech requires a nonempty jobId.");
67
+ }
68
+ const { intervalMs = TTS_POLL_INTERVAL_MS, maxPolls = TTS_MAX_POLLS } = options;
69
+ if (!Number.isInteger(intervalMs) || intervalMs < 0 || intervalMs > 2147483647 || !Number.isSafeInteger(maxPolls) || maxPolls < 1) {
70
+ invalid("waitForTextToSpeech requires a nonnegative intervalMs and a positive maxPolls.");
71
+ }
72
+ let budgetSignal;
73
+ try {
74
+ return await withRequest(
75
+ { signal: options.signal, timeoutMs: options.timeoutMs ?? TTS_WAIT_TIMEOUT_MS },
76
+ async (signal) => {
77
+ budgetSignal = signal;
78
+ let consecutiveErrors = 0;
79
+ for (let attempt = 0; attempt < maxPolls; attempt++) {
80
+ throwIfAborted(signal);
81
+ let response;
82
+ try {
83
+ response = await api.getTextToSpeechResult({ jobId: params.jobId }, { signal });
84
+ consecutiveErrors = 0;
85
+ } catch (error) {
86
+ throwIfAborted(signal);
87
+ if (!(error instanceof ApiError) || !["network_error", "timeout"].includes(String(error.code)) || error.status !== void 0 || ++consecutiveErrors >= 3) throw error;
88
+ }
89
+ if (response) {
90
+ const task = response.data;
91
+ if (task.status === -1) throw taskFailure(task);
92
+ if (task.status === 10 && task.result) return response;
93
+ }
94
+ if (attempt < maxPolls - 1) await delay(intervalMs, signal);
95
+ }
96
+ throw timeoutFailure();
97
+ }
98
+ );
99
+ } catch (error) {
100
+ if (error instanceof ApiError && error.code === "timeout" && (budgetSignal == null ? void 0 : budgetSignal.aborted)) throw timeoutFailure();
101
+ throw error;
102
+ }
103
+ }
104
+ export {
105
+ classifyTextToSpeechFailure,
106
+ waitForTextToSpeech
107
+ };
@@ -15,7 +15,7 @@ function createUsageReportingApi(getContext) {
15
15
  if (params && typeof params === "object") (_b = context.capture) == null ? void 0 : _b.call(context, params);
16
16
  } catch {
17
17
  }
18
- if (!params || typeof params !== "object" || Array.isArray(params) || Object.keys(params).some((key) => !["sum_key", "title", "data", "flow", "timings", "error"].includes(key)) || typeof params.sum_key !== "string" || !/^[a-zA-Z0-9_.:-]{1,64}$/.test(params.sum_key) || typeof params.title !== "string" || !params.title.trim() || params.data != null && (typeof params.data !== "object" || Array.isArray(params.data))) return false;
18
+ if (!params || typeof params !== "object" || Array.isArray(params) || Object.keys(params).some((key) => !["sum_key", "title", "data", "flow", "timings", "error", "payload"].includes(key)) || typeof params.sum_key !== "string" || !/^[a-zA-Z0-9_.:-]{1,64}$/.test(params.sum_key) || typeof params.title !== "string" || !params.title.trim() || params.data != null && (typeof params.data !== "object" || Array.isArray(params.data))) return false;
19
19
  const appKey = config.appKey ?? `${context.productName}_canva`;
20
20
  if (typeof appKey !== "string" || !/^[a-zA-Z0-9_.:-]{1,128}$/.test(appKey)) return false;
21
21
  const timeoutMs = options.timeoutMs ?? 4e3;
package/dist/index.js CHANGED
@@ -1,19 +1,27 @@
1
1
  import { YiChongCanvaProvider } from "./login/privider.js";
2
2
  import { YiChongCanvaContext } from "./login/context.js";
3
3
  import { useYiChongCanva } from "./login/use_canva.js";
4
- import { ApiError, isAbortError } from "./api/error.js";
4
+ import { PRICING_LANGUAGE_BASE_URL, loadPricingUnit } from "./login/pricing_unit.js";
5
+ import { ApiError, getBackendErrorCode, getDisplayMessage, isAbortError, isPolicyBlocked } from "./api/error.js";
5
6
  import { getPredictionOutputUrl } from "./api/predictions.js";
7
+ import { classifyTextToSpeechFailure } from "./api/tts_task.js";
6
8
  import { REPORT_STAGES, StageError, createStageTimer, isReportStage, toErrorCode } from "./api/telemetry/stage.js";
7
9
  export {
8
10
  ApiError,
11
+ PRICING_LANGUAGE_BASE_URL,
9
12
  REPORT_STAGES,
10
13
  StageError,
11
14
  YiChongCanvaContext,
12
15
  YiChongCanvaProvider,
16
+ classifyTextToSpeechFailure,
13
17
  createStageTimer,
18
+ getBackendErrorCode,
19
+ getDisplayMessage,
14
20
  getPredictionOutputUrl,
15
21
  isAbortError,
22
+ isPolicyBlocked,
16
23
  isReportStage,
24
+ loadPricingUnit,
17
25
  toErrorCode,
18
26
  useYiChongCanva
19
27
  };
@@ -34,6 +34,7 @@ const YiChongCanvaContext = React.createContext(
34
34
  },
35
35
  loginStatus: "idle",
36
36
  accountError: null,
37
+ pricingUnit: null,
37
38
  manualLogin: () => {
38
39
  },
39
40
  createSpecifyPrediction: async () => {
@@ -69,6 +70,9 @@ const YiChongCanvaContext = React.createContext(
69
70
  getTextToSpeechResult: async () => {
70
71
  throw new ApiError("Wrap your components in YiChongCanvaProvider first.", "provider_missing");
71
72
  },
73
+ waitForTextToSpeech: async () => {
74
+ throw new ApiError("Wrap your components in YiChongCanvaProvider first.", "provider_missing");
75
+ },
72
76
  reportError: async () => {
73
77
  throw new ApiError("Wrap your components in YiChongCanvaProvider first.", "provider_missing");
74
78
  },
@@ -7,15 +7,17 @@ const headers = {
7
7
  };
8
8
  const baseUrl = "https://usa.imgkits.com/";
9
9
  function getUserIds(token, appId, context, options = {}) {
10
- const queryString = new URLSearchParams({
11
- canva_user_token: token,
12
- appid: appId
13
- }).toString();
14
- const url = `https://canva.livepolls.app/getUserIdByAppid?${queryString}`;
10
+ const url = "https://canva.livepolls.app/getUserIdByAppid";
15
11
  return accountRequest({
16
12
  url,
17
- method: "GET",
18
- headers,
13
+ method: "POST",
14
+ headers: {
15
+ ...headers,
16
+ Authorization: `Bearer ${token}`
17
+ },
18
+ body: JSON.stringify({
19
+ appid: appId
20
+ }),
19
21
  redirect: "follow"
20
22
  }, context, "canva_identity", options, (body) => isObject(body.verified) && typeof body.verified.userId === "string" && !!body.verified.userId);
21
23
  }
@@ -0,0 +1,48 @@
1
+ import { withRequest } from "../api/transport.js";
2
+ const PRICING_LANGUAGE_BASE_URL = "https://project.deletetweets.ai/yichong_pricing_language";
3
+ const channelPattern = /^[a-z0-9_]{1,64}$/;
4
+ const languagePattern = /^[a-z]{2,3}$/;
5
+ const TIMEOUT_MS = 1e4;
6
+ const MAX_UNIT_LENGTH = 40;
7
+ function cleanUnit(value) {
8
+ if (typeof value !== "string") return void 0;
9
+ const text = value.trim();
10
+ return text && text.length <= MAX_UNIT_LENGTH && !/[<>{}]/.test(text) ? text : void 0;
11
+ }
12
+ async function fetchUnit(channel, lang, signal) {
13
+ return withRequest({ signal, timeoutMs: TIMEOUT_MS }, async (requestSignal) => {
14
+ const response = await fetch(`${PRICING_LANGUAGE_BASE_URL}/${channel}/${lang}.json`, {
15
+ cache: "no-cache",
16
+ credentials: "omit",
17
+ redirect: "error",
18
+ signal: requestSignal
19
+ });
20
+ if (!response.ok) return null;
21
+ const body = await response.json().catch(() => null);
22
+ const config = body !== null && typeof body === "object" ? body.config : void 0;
23
+ const fields = config !== null && typeof config === "object" ? config : {};
24
+ const unitNoun = cleanUnit(fields.unit);
25
+ if (!unitNoun) return null;
26
+ return { unitNoun, unitNounPlural: cleanUnit(fields.plural_unit) ?? unitNoun, locale: lang };
27
+ });
28
+ }
29
+ async function loadPricingUnit(channel, locale, signal) {
30
+ var _a;
31
+ if (!channelPattern.test(channel)) return null;
32
+ const primary = ((_a = locale.split("-")[0]) == null ? void 0 : _a.toLowerCase()) ?? "";
33
+ const candidates = languagePattern.test(primary) && primary !== "en" ? [primary, "en"] : ["en"];
34
+ for (const lang of candidates) {
35
+ if (signal == null ? void 0 : signal.aborted) return null;
36
+ try {
37
+ const unit = await fetchUnit(channel, lang, signal);
38
+ if (unit) return unit;
39
+ } catch {
40
+ if (signal == null ? void 0 : signal.aborted) return null;
41
+ }
42
+ }
43
+ return null;
44
+ }
45
+ export {
46
+ PRICING_LANGUAGE_BASE_URL,
47
+ loadPricingUnit
48
+ };
@@ -16,12 +16,14 @@ import { createErrorReportingApi } from "../api/reporting.js";
16
16
  import { createUsageReportingApi } from "../api/usage_reporting.js";
17
17
  import { createTelemetry } from "../api/telemetry/client.js";
18
18
  import { mapError, mapUsage } from "../api/telemetry/map_legacy.js";
19
+ import { createPayloadRecorder, recordApi } from "../api/telemetry/payload_recorder.js";
19
20
  import { language } from "../api/request.js";
20
21
  import { isValidUsageCount, invalidUsageResult, skippedUsage, recordUsage } from "./consumption.js";
21
22
  import { readCache, writeCache, versionCacheKey, testCacheKey } from "./cache.js";
22
23
  import { ApiError } from "../api/error.js";
23
24
  import { withRequest, throwIfAborted } from "../api/transport.js";
24
25
  import { createAccountReporter, AccountRequestError, retryableAccountError, accountDelay } from "./account.js";
26
+ import { loadPricingUnit } from "./pricing_unit.js";
25
27
  let usageIdSequence = 0;
26
28
  function usageId() {
27
29
  try {
@@ -78,6 +80,8 @@ const YiChongCanvaProvider = ({
78
80
  const sessionStopRef = useRef(null);
79
81
  const [loginStatus, setLoginStatus] = useState("idle");
80
82
  const [accountError, setAccountError] = useState(null);
83
+ const [pricingUnit, setPricingUnit] = useState(null);
84
+ const pricingLocale = language(getLocale);
81
85
  const accountRunRef = useRef(null);
82
86
  const loginPendingRef = useRef(false);
83
87
  const mountedRef = useRef(true);
@@ -101,21 +105,26 @@ const YiChongCanvaProvider = ({
101
105
  // 切换应用的子组件 effect 可能早于清理 effect,不暴露上一应用的账户快照。
102
106
  userStatus: identityScopeRef.current === `${apiConfigRef.current.appId}|${apiConfigRef.current.productName}` ? userStatusRef.current : {}
103
107
  });
104
- const [predictionApi] = useState(() => createPredictionApi(getApiContext));
108
+ const [payloadRecorder] = useState(createPayloadRecorder);
109
+ const payloadEnabled = () => {
110
+ var _a, _b, _c;
111
+ return ((_a = telemetryConfigRef.current) == null ? void 0 : _a.enabled) === true && ((_b = telemetryConfigRef.current) == null ? void 0 : _b.payload) !== false && ((_c = apiConfigRef.current.usageReporting) == null ? void 0 : _c.enabled) !== false;
112
+ };
113
+ const [predictionApi] = useState(() => recordApi(createPredictionApi(getApiContext), payloadRecorder, payloadEnabled));
105
114
  const [textModerationApi] = useState(() => createTextModerationApi(getApiContext));
106
- const [vttApi] = useState(() => createVttApi(getApiContext));
115
+ const [vttApi] = useState(() => recordApi(createVttApi(getApiContext), payloadRecorder, payloadEnabled));
107
116
  const [contentExtractionApi] = useState(() => createContentExtractionApi(() => ({
108
117
  ...getApiContext(),
109
118
  apiBaseUrl: apiConfigRef.current.contentBaseUrl
110
119
  })));
111
- const [chatApi] = useState(() => createChatApi(() => ({
120
+ const [chatApi] = useState(() => recordApi(createChatApi(() => ({
112
121
  ...getApiContext(),
113
122
  apiBaseUrl: apiConfigRef.current.chatBaseUrl
114
- })));
115
- const [textToSpeechApi] = useState(() => createTextToSpeechApi(() => ({
123
+ })), payloadRecorder, payloadEnabled));
124
+ const [textToSpeechApi] = useState(() => recordApi(createTextToSpeechApi(() => ({
116
125
  ...getApiContext(),
117
126
  apiBaseUrl: apiConfigRef.current.ttsBaseUrl
118
- })));
127
+ })), payloadRecorder, payloadEnabled));
119
128
  const getUsageContext = () => {
120
129
  var _a;
121
130
  const context = getApiContext();
@@ -168,7 +177,17 @@ const YiChongCanvaProvider = ({
168
177
  }));
169
178
  const captureUsage = (params) => {
170
179
  const mapped = mapUsage(params);
171
- if (mapped) telemetry.capture(mapped);
180
+ if (!mapped) return;
181
+ try {
182
+ const operationId = mapped.params.operation_id;
183
+ if (params.sum_key === "generate_start") payloadRecorder.begin(operationId);
184
+ else if (params.sum_key === "generate_success" || params.sum_key === "generate_fail") {
185
+ const recorded = payloadRecorder.take(operationId);
186
+ if (recorded && mapped.params.payload === void 0 && payloadEnabled()) mapped.params.payload = recorded;
187
+ }
188
+ } catch {
189
+ }
190
+ telemetry.capture(mapped);
172
191
  };
173
192
  const [usageReportingApi] = useState(() => createUsageReportingApi(() => {
174
193
  var _a, _b, _c;
@@ -770,6 +789,13 @@ const YiChongCanvaProvider = ({
770
789
  return creditsRef.current;
771
790
  }
772
791
  };
792
+ useEffect(() => {
793
+ const controller = new AbortController();
794
+ void loadPricingUnit(productName, pricingLocale, controller.signal).then((unit) => {
795
+ if (!controller.signal.aborted) setPricingUnit({ productName, unit });
796
+ });
797
+ return () => controller.abort();
798
+ }, [productName, pricingLocale]);
773
799
  const getMonthlyUsageLimit = () => {
774
800
  const { profile } = userStatusRef.current;
775
801
  const { usage_limits } = profile || {};
@@ -824,6 +850,8 @@ const YiChongCanvaProvider = ({
824
850
  },
825
851
  loginStatus,
826
852
  accountError,
853
+ // 换语言期间先保留上一份单位,避免闪回 config.ts 的英文;换渠道时旧单位作废。
854
+ pricingUnit: (pricingUnit == null ? void 0 : pricingUnit.productName) === productName ? pricingUnit.unit : null,
827
855
  updateCredits,
828
856
  stopCurrentPolling: () => {
829
857
  var _a;
@@ -13,16 +13,40 @@ export declare class ApiError extends Error {
13
13
  readonly data?: Record<string, unknown>;
14
14
  /** Retry-After 响应头的秒数;工具包不会自动重试。 */
15
15
  readonly retryAfter?: number;
16
+ /** 后端 error_code(snake_case):创建失败取响应顶层,任务失败取任务对象。2.7.0 起。 */
17
+ readonly errorCode?: string;
18
+ /** 后端 trace_id,目前只有创建接口返回。2.7.0 起。 */
19
+ readonly traceId?: string;
20
+ /**
21
+ * message 是后端分级后的用户文案、可以原样展示时为 true(见 docs/前后端约定-错误文案msg分级.md)。
22
+ * SDK 本地错误、约定范围外的接口、后端尚未打开分级时恒为 false。界面取文案用 getDisplayMessage。2.7.0 起。
23
+ */
24
+ readonly displayable: boolean;
16
25
  /**
17
26
  * @param message 可展示的错误说明。
18
27
  * @param code 后端业务码或 SDK 标识,例如 invalid_request、timeout、network_error。
19
28
  * @param status 已取得的 HTTP 状态;请求发出前的错误等情况通常没有此值。
20
- * @param details 可选诊断数据和 Retry-After 秒数;仅提供信息,不触发重试。
29
+ * @param details 可选诊断数据、Retry-After 秒数和后端分级信息;仅提供信息,不触发重试。
21
30
  */
22
31
  constructor(message: string, code: string | number, status?: number | undefined, details?: {
23
32
  data?: Record<string, unknown>;
24
33
  retryAfter?: number;
34
+ errorCode?: unknown;
35
+ traceId?: unknown;
36
+ displayable?: boolean;
25
37
  });
26
38
  }
39
+ /**
40
+ * 能原样展示给用户的后端文案;没有时返回 "",由应用显示自己的翻译兜底。
41
+ * 只认 displayable 的 ApiError:SDK 本地英文错误、服务商原文、未分级的 msg 都返回 ""。
42
+ */
43
+ export declare function getDisplayMessage(error: unknown): string;
44
+ /** 后端 error_code;没有时返回 undefined。应用做逻辑判断只看它,不匹配文案。 */
45
+ export declare function getBackendErrorCode(error: unknown): string | undefined;
46
+ /**
47
+ * 内容违规:后端 error_code 为 content_policy_violation,或 StageError 的 code 为 POLICY_BLOCKED。
48
+ * StageError 定义在 telemetry/stage.ts 且依赖本文件,这里按 code 字段判断,避免循环依赖。
49
+ */
50
+ export declare function isPolicyBlocked(error: unknown): boolean;
27
51
  /** 仅识别主动取消;普通 DOMException(例如 SecurityError)或后端任务失败不应被静默忽略。 */
28
52
  export declare function isAbortError(error: unknown): boolean;
@@ -3,7 +3,8 @@
3
3
  * 实现工厂保持内部使用,业务通过 Provider 的 client 调用方法,共享登录身份和配置。
4
4
  * 参数、返回值及方法的 JSDoc 定义在 types.ts,会随声明文件发布供编辑器提示。
5
5
  */
6
- export { ApiError, isAbortError } from './error';
6
+ export { ApiError, getBackendErrorCode, getDisplayMessage, isAbortError, isPolicyBlocked } from './error';
7
7
  export { getPredictionOutputUrl } from './predictions';
8
+ export { classifyTextToSpeechFailure } from './tts_task';
8
9
  export * from './telemetry';
9
- export type { ApiRequestOptions, ApiResponse, CancelPredictionResponse, ChatApi, ChatParams, ChatPayload, ChatResult, CreateTextToSpeechParams, CreateTextToSpeechResult, GetTextToSpeechResultParams, TextToSpeechApi, TextToSpeechResult, TextToSpeechTaskState, CreateVttParams, CreateVttResult, GetVttStatusParams, VttApi, VttStatusResult, VttTaskState, CompleteUploadParams, CompleteUploadResponse, ContentExtractParams, ContentExtractResult, ContentExtractionApi, TextCheckParams, CreateSpecifyPredictionParams, ErrorReportingApi, ErrorReportSource, GetPredictionParams, GeneratePresignedUrlParams, GetUploadUrlParams, InitiateUploadParams, InitiateUploadResponse, JsonObject, JsonValue, Prediction, PredictionApi, WaitForPredictionOptions, ReportErrorParams, ReportUsageParams, TelemetryApi, UsageReportingApi, UsageReportingConfig, ReportErrorResult, PresignedUrlResponse, TextModerationApi, TextModerationCategory, TextModerationDecision, TextModerationResult, UploadApi, UploadFileParams, UploadFileResult, UploadedPart, UploadPartUrlResponse, UploadProgress, UsageApi, UsageParams, UsageResponse, } from './types';
10
+ export type { ApiRequestOptions, ApiResponse, CancelPredictionResponse, ChatApi, ChatParams, ChatPayload, ChatResult, CreateTextToSpeechParams, CreateTextToSpeechResult, GetTextToSpeechResultParams, TextToSpeechApi, TextToSpeechFailureCode, TextToSpeechResult, TextToSpeechTaskState, WaitForTextToSpeechOptions, CreateVttParams, CreateVttResult, GetVttStatusParams, VttApi, VttStatusResult, VttTaskState, CompleteUploadParams, CompleteUploadResponse, ContentExtractParams, ContentExtractResult, ContentExtractionApi, TextCheckParams, CreateSpecifyPredictionParams, ErrorReportingApi, ErrorReportSource, GetPredictionParams, GeneratePresignedUrlParams, GetUploadUrlParams, InitiateUploadParams, InitiateUploadResponse, JsonObject, JsonValue, Prediction, PredictionApi, WaitForPredictionOptions, ReportErrorParams, ReportUsageParams, TelemetryApi, UsageReportingApi, UsageReportingConfig, ReportErrorResult, PresignedUrlResponse, TextModerationApi, TextModerationCategory, TextModerationDecision, TextModerationResult, UploadApi, UploadFileParams, UploadFileResult, UploadedPart, UploadPartUrlResponse, UploadProgress, UsageApi, UsageParams, UsageResponse, } from './types';
@@ -62,10 +62,14 @@ export declare function addContextQuery(url: URL, context: CommonRequestContext)
62
62
  /** 读取完整 JSON 正文;HTML 错误页或损坏 JSON 只产生统一错误,不把原始正文混进异常。 */
63
63
  export declare function readJson(response: Response): Promise<unknown>;
64
64
  /**
65
- * 尽量保留后端 msg / code 以及对象类型的诊断 data,供应用展示或识别业务失败。
65
+ * 尽量保留后端 msg / code / error_code / trace_id 以及对象类型的诊断 data,供应用展示或识别业务失败。
66
66
  * Retry-After 仅接受整数秒并作为提示返回;此处不会安排重试,也不解析 HTTP 日期格式。
67
+ * tiered 表示该接口属于 msg 分级约定(docs/前后端约定-错误文案msg分级.md):响应带 debug_msg 时
68
+ * 说明后端已打开分级、msg 可以原样展示。其它接口的 msg 仍可能是内部代号,displayable 恒为 false。
67
69
  */
68
- export declare function backendError(response: Response, payload: unknown, fallbackCode: string | number): ApiError;
70
+ export declare function backendError(response: Response, payload: unknown, fallbackCode: string | number, options?: {
71
+ tiered?: boolean;
72
+ }): ApiError;
69
73
  /**
70
74
  * AI 接口的公共 POST:注入鉴权、Channel、语言与通用 query,并校验响应包。
71
75
  * 旧 TTS 路由的 JWT 可选,其余保持原有 JWT 要求;账户归属不等于服务端身份验证。
@@ -0,0 +1,27 @@
1
+ type Entry = Record<string, unknown>;
2
+ interface Slot {
3
+ request: Entry[];
4
+ result: Entry[];
5
+ error: Entry[];
6
+ }
7
+ export interface PayloadRecorder {
8
+ /** generate_start:之后的接口调用记到这个操作下。 */
9
+ begin(operationId: string | undefined): void;
10
+ record(kind: keyof Slot, api: string, value: Entry): void;
11
+ /** generate_success / generate_fail:取出并清空该操作记到的内容;没有记录时返回 undefined。 */
12
+ take(operationId: string | undefined): Record<string, unknown> | undefined;
13
+ }
14
+ export declare function createPayloadRecorder(): PayloadRecorder;
15
+ /** 每个方法怎么取请求和结果;返回 undefined 表示这次不记(例如轮询中的中间状态)。 */
16
+ export interface RecordSpec {
17
+ request?: (params: unknown) => Entry | undefined;
18
+ result?: (response: unknown) => Entry | undefined;
19
+ }
20
+ /** 默认采集的接口。上传、审核、额度等不记:它们的输入已经包含在生成请求里,或与排查生成无关。 */
21
+ export declare const RECORD_SPECS: Record<string, RecordSpec>;
22
+ /**
23
+ * 返回一个包装后的副本:调用照常转发,原返回值和抛错不变;记录失败也不影响调用。
24
+ * enabled 每次调用时读取,关闭后不再记录。
25
+ */
26
+ export declare function recordApi<T extends object>(api: T, recorder: PayloadRecorder, enabled: () => boolean, specs?: Record<string, RecordSpec>): T;
27
+ export {};
@@ -9,3 +9,11 @@ export declare function cleanTimings(input: unknown): TelemetryTimings | undefin
9
9
  export declare function cleanDuration(value: unknown): number | undefined;
10
10
  /** 从应用传入的错误描述生成上报对象;stack 只在 expected=false 时保留。 */
11
11
  export declare function cleanError(input: TelemetryErrorInput, secrets: readonly string[]): TelemetryErrorPayload;
12
+ /** 单条事件 payload 序列化后的上限(UTF-8 字节);服务端上限相同。 */
13
+ export declare const MAX_PAYLOAD_BYTES: number;
14
+ /**
15
+ * 生成可入库的 payload 副本:普通对象/数组,最多 7 层、100 个字段、数组 20 项;
16
+ * 凭据键整值替换,已知 token / JWT / Bearer 替换,data:/blob: 地址只留类型,提示词和 http(s) 地址保留。
17
+ * 超过 8 KB 时逐步缩短长字符串,仍超出则只记 { _truncated: true }。不是对象时返回 undefined。
18
+ */
19
+ export declare function cleanPayload(input: unknown, secrets: readonly string[]): Record<string, unknown> | undefined;
@@ -18,8 +18,9 @@ export declare class StageError extends Error {
18
18
  });
19
19
  }
20
20
  /**
21
- * 按 01 第 5 节的顺序推断错误码:StageError → SDK / Canva 的字符串错误码转大写 → <STAGE>_FAILED → UNKNOWN。
22
- * 数字业务码不当作错误码(放 backend_code),避免后端自由文本进入分组键。
21
+ * 按 01 第 5 节的顺序推断错误码:StageError → 后端 error_code → SDK / Canva 的字符串错误码转大写
22
+ * → <STAGE>_FAILED → UNKNOWN。数字业务码不当作错误码(放 backend_code),避免后端自由文本进入分组键。
23
+ * 后端的 content_policy_violation 记为 POLICY_BLOCKED(generate_blocked,不告警),应用不用再匹配 E005。
23
24
  */
24
25
  export declare function toErrorCode(error: unknown, stage?: ReportStage): string;
25
26
  /**
@@ -33,6 +33,12 @@ export interface TrackParams {
33
33
  timings?: TelemetryTimings;
34
34
  duration_ms?: number;
35
35
  error?: TelemetryErrorInput;
36
+ /**
37
+ * 2.8.0 起:用户这次请求的原始参数(提示词、图片地址、比例等),供后台「事件详情」排查。
38
+ * 只去掉凭据(token / JWT / Bearer / 密码类键名)和 data:/blob: 地址,序列化后最多 8 KB。
39
+ * 服务端只保留 7 天。只给需要排查的事件传,例如 generate_start / generate_fail。
40
+ */
41
+ payload?: Record<string, unknown>;
36
42
  }
37
43
  /** Provider 的 telemetry 属性。 */
38
44
  export interface TelemetryConfig {
@@ -40,6 +46,11 @@ export interface TelemetryConfig {
40
46
  enabled?: boolean;
41
47
  /** 默认 https://telemetry.imgkits.com/v1/events;只接受 https,本地调试允许 http://localhost。 */
42
48
  endpoint?: string;
49
+ /**
50
+ * 2.8.0 起,默认 true:自动采集生成类接口(prediction / chat / TTS / VTT)的请求参数和最终结果,
51
+ * 应用上报 generate_success / generate_fail 且没传 payload 时自动填上。false 时只发应用自己传的 payload。
52
+ */
53
+ payload?: boolean;
43
54
  }
44
55
  /** 发送到采集 Worker 的单条事件(信封 + 事件 + 错误)。 */
45
56
  export interface TelemetryEvent {
@@ -70,6 +81,7 @@ export interface TelemetryEvent {
70
81
  timings?: TelemetryTimings;
71
82
  duration_ms?: number;
72
83
  error?: TelemetryErrorPayload;
84
+ payload?: Record<string, unknown>;
73
85
  repeat_count: number;
74
86
  dropped_props: number;
75
87
  }
@@ -1,7 +1,8 @@
1
1
  import { ApiContext } from './request';
2
2
  import { TextToSpeechApi } from './types';
3
3
  /**
4
- * 封装现有异步 TTS 创建/查询协议;仅请求一次,不附加轮询、重试或额外消费。
4
+ * 封装现有异步 TTS 创建/查询协议;create / getTextToSpeechResult 仅请求一次,
5
+ * waitForTextToSpeech 是显式调用的等待流程(2.7.1 起),不额外消费。
5
6
  * guid 由请求层使用当前系统 uid 注入,调用方不能覆盖 guid 或改变计费分支的 app_id。
6
7
  * 语音、语言与上游模型的默认选择继续由后端负责;SDK 不维护会过时的语音枚举。
7
8
  */
@@ -0,0 +1,16 @@
1
+ import { ApiResponse, GetTextToSpeechResultParams, TextToSpeechApi, TextToSpeechFailureCode, TextToSpeechResult, WaitForTextToSpeechOptions } from './types';
2
+ /**
3
+ * 把 TTS 任务失败原因归成三类,供应用按 code 选文案或显示升级入口。
4
+ * 优先任务上的 error_code(已知取值才用),没有再按 remark 的稳定关键字,都拿不准归 tts_failed。
5
+ * 只看字段,不匹配后端返回的整句用户文案;remark 原文不上屏。
6
+ */
7
+ export declare function classifyTextToSpeechFailure(task: unknown): {
8
+ code: TextToSpeechFailureCode;
9
+ };
10
+ /**
11
+ * 轮询同一个 TTS 任务直到结束:status=10 且有 result 时返回该次响应。
12
+ * status=-1 立即抛分类后的 ApiError(不空等到轮询次数用完);只重试连接失败和单次超时,
13
+ * 且连续 3 次即停,后端业务错误和 HTTP 错误直接保留。轮询次数用完抛 tts_timeout,
14
+ * 主动取消抛 aborted。停止等待不会取消后端任务,也不额外消费。
15
+ */
16
+ export declare function waitForTextToSpeech(api: Pick<TextToSpeechApi, "getTextToSpeechResult">, params: GetTextToSpeechResultParams, options?: WaitForTextToSpeechOptions): Promise<ApiResponse<TextToSpeechResult>>;
@@ -133,6 +133,12 @@ export interface Prediction {
133
133
  error?: string | null;
134
134
  /** 部分后端返回的补充错误文案。 */
135
135
  error_msg?: string | null;
136
+ /** 失败任务的统一错误码(msg 分级打开后才有);有它时 error_msg / error 已是用户文案。2.7.0 起。 */
137
+ error_code?: string;
138
+ /** 改写前的 error 原文,只用于排查,不要展示。2.7.0 起。 */
139
+ raw_error?: string | null;
140
+ /** 改写前的 error_msg 原文,只用于排查,不要展示。2.7.0 起。 */
141
+ raw_error_msg?: string | null;
136
142
  /** 后端附加的平台标识。 */
137
143
  $platform?: string;
138
144
  /** 后端附加的模型标识。 */
@@ -566,6 +572,20 @@ export interface TextToSpeechResult extends TextToSpeechTaskState {
566
572
  /** 后端生成的音频 URL;排队、处理中或失败时可以为 null 或空字符串。 */
567
573
  result: string | null;
568
574
  }
575
+ /**
576
+ * TTS 任务失败的三类原因,由 classifyTextToSpeechFailure / waitForTextToSpeech 给出。
577
+ * 应用按它选文案:额度不足给升级入口,内容违规用政策文案,其余用通用兜底。
578
+ */
579
+ export type TextToSpeechFailureCode = "quota_exceeded" | "content_policy_violation" | "tts_failed";
580
+ /** 等待 TTS 任务完成的轮询节奏;只决定本地查询次数,不改变后端额度检查和计费。 */
581
+ export interface WaitForTextToSpeechOptions extends ApiRequestOptions {
582
+ /** 两次查询之间的间隔,默认 3000 毫秒;允许 0,不在最后一次查询后继续等待。 */
583
+ intervalMs?: number;
584
+ /** 查询次数上限,默认 50;失败的查询也计入次数,必须为正整数。 */
585
+ maxPolls?: number;
586
+ /** 所有查询及间隔共用的总等待预算,默认 180000 毫秒;单次查询仍最多等待 60 秒。 */
587
+ timeoutMs?: number;
588
+ }
569
589
  /** 异步文字转语音;保留现有 /api/text-to-speech 路径及 code/msg/data 响应包。 */
570
590
  export interface TextToSpeechApi {
571
591
  /**
@@ -584,6 +604,18 @@ export interface TextToSpeechApi {
584
604
  * status=10 时读取 result;status=-1 时展示 remark。失败任务原样返回,不作为接口异常抛出。
585
605
  */
586
606
  getTextToSpeechResult(params: GetTextToSpeechResultParams, options?: ApiRequestOptions): Promise<ApiResponse<TextToSpeechResult>>;
607
+ /**
608
+ * 轮询同一个任务直到结束(2.7.1 起),默认每 3 秒查一次、最多 50 次,总预算 180 秒。
609
+ * status=10 且有 result 时返回该次响应;status=-1 立即抛 ApiError,code 为 classifyTextToSpeechFailure
610
+ * 的分类结果(quota_exceeded / content_policy_violation / tts_failed),status 是任务状态而非 HTTP 状态,
611
+ * displayable 恒为 false(remark 原文不上屏)。
612
+ * 只重试连接失败和单次超时(连续 3 次即停);轮询次数用完抛 tts_timeout,主动取消抛 aborted。
613
+ * 停止等待不会取消后端任务,也不额外调用消费接口。
614
+ * @example
615
+ * const { data } = await client.waitForTextToSpeech({ jobId });
616
+ * const audioUrl = data.result;
617
+ */
618
+ waitForTextToSpeech(params: GetTextToSpeechResultParams, options?: WaitForTextToSpeechOptions): Promise<ApiResponse<TextToSpeechResult>>;
587
619
  }
588
620
  /** 行为统计配置;独立于消费记账与飞书错误告警,关闭后不会发出埋点请求。 */
589
621
  export interface UsageReportingConfig {
@@ -612,6 +644,11 @@ export interface ReportUsageParams {
612
644
  timings?: TelemetryTimings;
613
645
  /** 2.6.0 起,只进新通道:失败事件的错误描述。code 为 POLICY_BLOCKED 的 generate_fail 在新通道记为 generate_blocked。 */
614
646
  error?: TelemetryErrorInput;
647
+ /**
648
+ * 2.8.0 起,只进新通道(旧 GET 统计忽略):用户这次请求的原始参数,供后台「事件详情」排查。
649
+ * 与 data 不同,提示词和 http(s) 地址会保留;只去掉凭据和 data:/blob: 地址,最多 8 KB,服务端保留 7 天。
650
+ */
651
+ payload?: Record<string, unknown>;
615
652
  }
616
653
  /** 新通道(canva.v1)专用的上报方法;默认关闭,见 Provider 的 telemetry 属性。 */
617
654
  export interface TelemetryApi {
@@ -1,6 +1,7 @@
1
1
  import { default as React } from 'react';
2
2
  import { AccountError } from './account';
3
3
  import { UseResult } from './consumption';
4
+ import { PricingUnit } from './pricing_unit';
4
5
  import { ChatApi, ContentExtractionApi, ErrorReportingApi, PredictionApi, TelemetryApi, TextModerationApi, TextToSpeechApi, UploadApi, UsageApi, UsageReportingApi, VttApi } from '../api/types';
5
6
  import { canUseError, CheckoutSessionOptions, TestMode, UserStatus } from './interface';
6
7
  /**
@@ -73,6 +74,11 @@ export interface YiChongCanvaContextType extends PredictionApi, TextModerationAp
73
74
  loginStatus: "success" | "error" | "loading" | "idle";
74
75
  /** 最近一次账户登录/刷新/支付检查失败;开始重试或成功后清除。自动上报不依赖 Footer 挂载。 */
75
76
  accountError: AccountError | null;
77
+ /**
78
+ * 2.7.0:定价语言包里的计量单位,按 productName 和界面语言(主语言,没有退 en)读取。
79
+ * 读取中或拿不到时为 null,应用退回 config.ts 的 unitConfig;改定价单位不需要前端发版。
80
+ */
81
+ pricingUnit: PricingUnit | null;
76
82
  /** 手动启动登录,参数是失败后的重试次数(默认 1,另有首次请求);通过状态而非 Promise 获取结果。 */
77
83
  manualLogin: (_retry?: number) => void;
78
84
  }
@@ -5,3 +5,5 @@ export * from './context';
5
5
  export * from './use_canva';
6
6
  export type { AccountError, AccountStage, AccountOperation } from './account';
7
7
  export type { UseResult, UseChannel, UseError, UseSkipReason, ConfirmedUsage } from './consumption';
8
+ export { loadPricingUnit, PRICING_LANGUAGE_BASE_URL } from './pricing_unit';
9
+ export type { PricingUnit } from './pricing_unit';
@@ -0,0 +1,15 @@
1
+ /**
2
+ * 定价语言包里的计量单位(2.7.0 起)。Footer / QuotaAlert 优先用它,拿不到时用应用 config.ts 的 unitConfig。
3
+ * 来源与定价页同一份文件,改了定价单位不用前端发版;locale 是实际取到的语言包(例如 zh、en)。
4
+ */
5
+ export interface PricingUnit {
6
+ unitNoun: string;
7
+ unitNounPlural: string;
8
+ locale: string;
9
+ }
10
+ export declare const PRICING_LANGUAGE_BASE_URL = "https://project.deletetweets.ai/yichong_pricing_language";
11
+ /**
12
+ * 先取界面语言的主语言(zh-TW → zh、pt-BR → pt),没有再退到 en;都拿不到返回 null。
13
+ * 404、断网、超时、格式不对都只返回 null,不抛错、不上报:部分渠道本来就没有定价语言包。
14
+ */
15
+ export declare function loadPricingUnit(channel: string, locale: string, signal?: AbortSignal): Promise<PricingUnit | null>;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "yichong-canva2",
3
- "version": "2.6.0",
3
+ "version": "2.8.0",
4
4
  "type": "module",
5
5
  "main": "./dist/index.js",
6
6
  "module": "./dist/index.js",