yichong-canva2 2.7.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,10 @@
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
+
5
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 起)」。
6
10
 
7
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 起)」。
@@ -650,7 +654,25 @@ export function SpeechPanel() {
650
654
 
651
655
  创建返回任务 `jobId`;查询保留 `jobId/status/status_str/remark/result`。状态为 `0` 等待、`2` 处理中、`10` 完成、`-1` 失败。`code=0` 不是生成完成,创建本身也可能返回 `status=-1`,因此创建和查询均要检查任务状态。`result` 是音频 URL 字符串或 `null`,直接用于播放器或后续导入流程,无需 JSON.parse。
652
656
 
653
- 默认每次请求超时 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`,等后端补约定后再收敛关键字。
654
676
 
655
677
  ## 文本审核
656
678
 
@@ -915,3 +937,39 @@ client.track({ name: "quota_blocked", props: { cost: 2, state: "insufficient" }
915
937
  - `props` 只保留扁平的字符串、数字、布尔或 null,最多 20 个;键名命中 `prompt`、`text`、`url`、`token`、`file_name` 等敏感词,或值里含 URL、邮箱、JWT 时,整键丢弃。
916
938
  - `env`:页面运行在 localhost、测试模式(`updateTestMode`)或 `mode: "demo"` 时为 `dev`;审核期为 `review`;其余为 `production`。注意发布产物的 `NODE_ENV` 固定为 production,不能据此判断开发环境。
917
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 天)。
@@ -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.7.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)
@@ -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.7.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
+ };
@@ -99,9 +99,68 @@ function cleanError(input, secrets) {
99
99
  }
100
100
  return payload;
101
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
+ }
102
159
  export {
160
+ MAX_PAYLOAD_BYTES,
103
161
  cleanDuration,
104
162
  cleanError,
163
+ cleanPayload,
105
164
  cleanProps,
106
165
  cleanTimings,
107
166
  isSensitiveKey
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
@@ -4,6 +4,7 @@ import { useYiChongCanva } from "./login/use_canva.js";
4
4
  import { PRICING_LANGUAGE_BASE_URL, loadPricingUnit } from "./login/pricing_unit.js";
5
5
  import { ApiError, getBackendErrorCode, getDisplayMessage, isAbortError, isPolicyBlocked } from "./api/error.js";
6
6
  import { getPredictionOutputUrl } from "./api/predictions.js";
7
+ import { classifyTextToSpeechFailure } from "./api/tts_task.js";
7
8
  import { REPORT_STAGES, StageError, createStageTimer, isReportStage, toErrorCode } from "./api/telemetry/stage.js";
8
9
  export {
9
10
  ApiError,
@@ -12,6 +13,7 @@ export {
12
13
  StageError,
13
14
  YiChongCanvaContext,
14
15
  YiChongCanvaProvider,
16
+ classifyTextToSpeechFailure,
15
17
  createStageTimer,
16
18
  getBackendErrorCode,
17
19
  getDisplayMessage,
@@ -70,6 +70,9 @@ const YiChongCanvaContext = React.createContext(
70
70
  getTextToSpeechResult: async () => {
71
71
  throw new ApiError("Wrap your components in YiChongCanvaProvider first.", "provider_missing");
72
72
  },
73
+ waitForTextToSpeech: async () => {
74
+ throw new ApiError("Wrap your components in YiChongCanvaProvider first.", "provider_missing");
75
+ },
73
76
  reportError: async () => {
74
77
  throw new ApiError("Wrap your components in YiChongCanvaProvider first.", "provider_missing");
75
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
  }
@@ -16,6 +16,7 @@ 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";
@@ -104,21 +105,26 @@ const YiChongCanvaProvider = ({
104
105
  // 切换应用的子组件 effect 可能早于清理 effect,不暴露上一应用的账户快照。
105
106
  userStatus: identityScopeRef.current === `${apiConfigRef.current.appId}|${apiConfigRef.current.productName}` ? userStatusRef.current : {}
106
107
  });
107
- 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));
108
114
  const [textModerationApi] = useState(() => createTextModerationApi(getApiContext));
109
- const [vttApi] = useState(() => createVttApi(getApiContext));
115
+ const [vttApi] = useState(() => recordApi(createVttApi(getApiContext), payloadRecorder, payloadEnabled));
110
116
  const [contentExtractionApi] = useState(() => createContentExtractionApi(() => ({
111
117
  ...getApiContext(),
112
118
  apiBaseUrl: apiConfigRef.current.contentBaseUrl
113
119
  })));
114
- const [chatApi] = useState(() => createChatApi(() => ({
120
+ const [chatApi] = useState(() => recordApi(createChatApi(() => ({
115
121
  ...getApiContext(),
116
122
  apiBaseUrl: apiConfigRef.current.chatBaseUrl
117
- })));
118
- const [textToSpeechApi] = useState(() => createTextToSpeechApi(() => ({
123
+ })), payloadRecorder, payloadEnabled));
124
+ const [textToSpeechApi] = useState(() => recordApi(createTextToSpeechApi(() => ({
119
125
  ...getApiContext(),
120
126
  apiBaseUrl: apiConfigRef.current.ttsBaseUrl
121
- })));
127
+ })), payloadRecorder, payloadEnabled));
122
128
  const getUsageContext = () => {
123
129
  var _a;
124
130
  const context = getApiContext();
@@ -171,7 +177,17 @@ const YiChongCanvaProvider = ({
171
177
  }));
172
178
  const captureUsage = (params) => {
173
179
  const mapped = mapUsage(params);
174
- 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);
175
191
  };
176
192
  const [usageReportingApi] = useState(() => createUsageReportingApi(() => {
177
193
  var _a, _b, _c;
@@ -5,5 +5,6 @@
5
5
  */
6
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';
@@ -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;
@@ -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>>;
@@ -572,6 +572,20 @@ export interface TextToSpeechResult extends TextToSpeechTaskState {
572
572
  /** 后端生成的音频 URL;排队、处理中或失败时可以为 null 或空字符串。 */
573
573
  result: string | null;
574
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
+ }
575
589
  /** 异步文字转语音;保留现有 /api/text-to-speech 路径及 code/msg/data 响应包。 */
576
590
  export interface TextToSpeechApi {
577
591
  /**
@@ -590,6 +604,18 @@ export interface TextToSpeechApi {
590
604
  * status=10 时读取 result;status=-1 时展示 remark。失败任务原样返回,不作为接口异常抛出。
591
605
  */
592
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>>;
593
619
  }
594
620
  /** 行为统计配置;独立于消费记账与飞书错误告警,关闭后不会发出埋点请求。 */
595
621
  export interface UsageReportingConfig {
@@ -618,6 +644,11 @@ export interface ReportUsageParams {
618
644
  timings?: TelemetryTimings;
619
645
  /** 2.6.0 起,只进新通道:失败事件的错误描述。code 为 POLICY_BLOCKED 的 generate_fail 在新通道记为 generate_blocked。 */
620
646
  error?: TelemetryErrorInput;
647
+ /**
648
+ * 2.8.0 起,只进新通道(旧 GET 统计忽略):用户这次请求的原始参数,供后台「事件详情」排查。
649
+ * 与 data 不同,提示词和 http(s) 地址会保留;只去掉凭据和 data:/blob: 地址,最多 8 KB,服务端保留 7 天。
650
+ */
651
+ payload?: Record<string, unknown>;
621
652
  }
622
653
  /** 新通道(canva.v1)专用的上报方法;默认关闭,见 Provider 的 telemetry 属性。 */
623
654
  export interface TelemetryApi {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "yichong-canva2",
3
- "version": "2.7.0",
3
+ "version": "2.8.0",
4
4
  "type": "module",
5
5
  "main": "./dist/index.js",
6
6
  "module": "./dist/index.js",