yichong-canva2 2.5.1 → 2.6.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,8 @@
2
2
 
3
3
  使用一个 `YiChongCanvaProvider` 管理登录、订阅和额度,通过 `useYiChongCanva()` 直接调用后端接口。
4
4
 
5
+ **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
+
5
7
  **2.5.1**:只补类型、不改行为。`userStatus.profile` 增加后端 status 已返回的 `review?: boolean`(审核开关:true 审核期、false 正常运行、缺失为旧账户)、`canva_id?`、`created_at?`、`nextUsageResetTime?`。支付链接是否可点由应用按 `review === false || canAcceptPayments` 决定,SDK 不据此改变任何行为。
6
8
 
7
9
  **2.5.0 已发布(2026-10-16)**:消费不再自动重试,`use()` 返回可核对的 `UseResult`;账户与审核缓存按身份隔离。新增显式轮询 `waitForPrediction`、取消请求 `cancelPrediction`、结果地址/取消识别工具,以及 `uploadFile({ retention: "day30" })`。可直接 `npm install yichong-canva2@^2.5.0`;修改 SDK 源码时仍用 `npm pack` 或脚手架 `--sdk-path` 验证。
@@ -121,6 +123,7 @@ function GenerateButton() {
121
123
  | `client.getTextToSpeechResult({ jobId })`(2.4.0 起) | `POST {ttsBaseUrl}/api/text-to-speech/result` | `{ code: 0, msg, data: { jobId, status, status_str, result, remark } }` |
122
124
  | `client.reportUsage({ sum_key, title, data? })`(2.4.0 起) | `GET https://log.aibabygenerator.io/api/report` | `Promise<boolean>`;失败不抛错,不阻断业务 |
123
125
  | `client.reportError({ error, source?, stage?, api?, context? })` | `POST https://report.imgkits.com` | Worker 原始 `{ success: true, data: { code: 0, ... } }` 或过滤响应 |
126
+ | `client.track({ name, operation_id?, flow?, page?, props?, timings?, duration_ms?, error? })`(2.6.0 起) | 新通道 `POST https://telemetry.imgkits.com/v1/events`(批量) | `void`;只在 `telemetry.enabled` 时发送,永不抛错 |
124
127
  | `client.reduceFreeCnt({ cnt })` | `POST {baseUrl}/api/user/reduce-free-cnt` | `{ ok: 0, msg: "success" }` |
125
128
  | `client.addMonthlyUsage({ cnt })` | `POST {baseUrl}/api/user/add-monthly-usage` | `{ ok: 0, msg: "success" }` |
126
129
  | `client.addFreeUsageCnt({ cnt })` | `POST {baseUrl}/api/user/add-free-usage-cnt` | `{ ok: 0, msg: "success" }` |
@@ -808,3 +811,60 @@ void client.reportUsage({
808
811
  返回值为 `Promise<boolean>`:收到 HTTP 成功确认时为 true;关闭、非法参数、身份 getter/序列化异常、取消、网络等失败均为 false,不向业务抛错、不显示错误、不递归告警。通常 `void client.reportUsage(...)` 即可。默认每次请求 4 秒,网络/超时/429/5xx 最多重试一次,其他 4xx 不重试;第二参数 `{ signal, timeoutMs }` 可取消或缩短等待(1–4000 毫秒,每次)。
809
812
 
810
813
  只传枚举、计数、耗时、错误码等少量属性,不传提示词、完整 input/output、文件、资源地址、token、stack 或原始异常。SDK 会脱敏敏感字段和值,跳过 getter/toJSON/类实例,最多 3 层、30 个字段、数组 10 项、字符串 256 字符;最终 URL 上限 8192 字符,超长时先移除尾部业务属性。脱敏无法识别任意改名的用户文本,应用仍需只提供必要统计数据。统计失败不影响 Footer 原样式、加载状态或文案。
814
+
815
+ ## 新通道(2.6.0 起)
816
+
817
+ 新通道按 schema `canva.v1` 把行为和错误放进同一个事件流,批量发到 `https://telemetry.imgkits.com/v1/events`。完整设计见仓库 `docs/canva-telemetry/`(01 事件格式、02 SDK 上报层)。
818
+
819
+ **默认关闭。** 不传 `telemetry` 或 `enabled: false` 时不发出任何新通道请求。旧通道(GET 统计、飞书错误上报)在开启前后完全相同。`usageReporting={{ enabled: false }}` 同时关闭两条通道。
820
+
821
+ ```tsx
822
+ <YiChongCanvaProvider
823
+ appId="YOUR_CANVA_APP_ID"
824
+ productName="your_app_channel"
825
+ baseUrl="https://usa.imgkits.com/your_app_channel"
826
+ version={1}
827
+ telemetry={{ enabled: true }} // 默认 false;endpoint 默认 https://telemetry.imgkits.com/v1/events
828
+ >
829
+ <App />
830
+ </YiChongCanvaProvider>
831
+ ```
832
+
833
+ 开启后:
834
+
835
+ - `reportUsage` 和 `reportError` 的每次调用都会额外登记一条新通道事件(`reportError` 记为 `app_error`);`generate_retry` 不进新通道(由 `generate_start` 的 `retry_of` 表达);`data.mode: "demo"` 的事件记为 `env: "dev"`。
836
+ - Provider 的账户事件(`app_open`、`login_*`、`account_*`)自动进入新通道;`login_fail` / `account_fail` 带 `error`(`stage: "account"`)。
837
+ - `use(cnt, force, notUpload, { operationId })` 结束后自动发 `consume_result`(`status`、`cnt`;失败或未知时带 `error`)。不改变扣费行为。
838
+
839
+ 新增的可选字段和方法:
840
+
841
+ ```ts
842
+ import { StageError, createStageTimer, toErrorCode } from "yichong-canva2";
843
+
844
+ // 1. 记录每一步耗时;失败时抛 StageError,携带失败步骤和错误码
845
+ const timer = createStageTimer();
846
+ try {
847
+ const uploaded = await timer.run("upload", () => client.uploadFile({ file }, { signal }));
848
+ // ...
849
+ } catch (error) {
850
+ throw new StageError(error, { stage: "upload", code: toErrorCode(error, "upload") });
851
+ }
852
+
853
+ // 2. reportUsage 新增 flow / timings / error,只进新通道
854
+ void client.reportUsage({
855
+ sum_key: "generate_fail", title: "Generation failed",
856
+ data: { operation_id: operationId, duration_ms },
857
+ timings: timer.timings,
858
+ error: { stage: "upload", cause: error }, // code 省略时由 SDK 推断;cause 为 StageError 时直接取它的 stage/code
859
+ });
860
+
861
+ // 3. 新事件和自定义事件用 track,只进新通道,同步返回、永不抛错
862
+ client.track({ name: "quota_blocked", props: { cost: 2, state: "insufficient" } });
863
+ ```
864
+
865
+ - 应用使用这些新字段或方法时,依赖须为 `yichong-canva2@^2.6.0`。旧版本的 `reportUsage` 收到未知字段会返回 `false` 且不发送。
866
+ - `stage` 只能取词表:`input_read`、`selection_read`、`upload`、`text_check`、`content_extract`、`chat`、`create_prediction`、`wait_prediction`、`cancel_prediction`、`tts`、`vtt`、`direct_api`、`parse_result`、`download_result`、`local_render`、`insert`、`consume`、`render`、`account`、`unknown`。
867
+ - 审核拦截请用错误码 `POLICY_BLOCKED`:`generate_fail` 带这个错误码时,新通道记为 `generate_blocked`。
868
+ - `props` 只保留扁平的字符串、数字、布尔或 null,最多 20 个;键名命中 `prompt`、`text`、`url`、`token`、`file_name` 等敏感词,或值里含 URL、邮箱、JWT 时,整键丢弃。
869
+ - `env`:页面运行在 localhost、测试模式(`updateTestMode`)或 `mode: "demo"` 时为 `dev`;审核期为 `review`;其余为 `production`。注意发布产物的 `NODE_ENV` 固定为 production,不能据此判断开发环境。
870
+ - 发送:满 20 条或 5 秒发一批,页面隐藏和 Provider 卸载时用 `keepalive` 发送剩余事件;只对网络、超时、429、5xx 重试两次;服务端返回 503 或 `pause_seconds` 后本会话停止发送;每会话最多 500 条;同一错误 60 秒内合并为 `repeat_count`。不读写本地存储。
@@ -8,20 +8,24 @@ const reportToken = "base64:MsUJo+qAhIVGPx52r1mbxCYn5YbWtCx8FQ7pTaHEvRo=";
8
8
  function createErrorReportingApi(getContext) {
9
9
  return {
10
10
  async reportError(params, options) {
11
- var _a, _b, _c;
11
+ var _a, _b, _c, _d;
12
12
  const context = getContext();
13
+ try {
14
+ if (params && typeof params === "object") (_a = context.capture) == null ? void 0 : _a.call(context, params);
15
+ } catch {
16
+ }
13
17
  if (!isNonemptyString(context.productName) || context.productName.length > 64 || !isNonemptyString(context.appId) || context.appId.length > 64 || !Number.isFinite(context.version) || String(context.version).length > 64) {
14
18
  invalid("Error reporting requires the Provider productName, appId and version.");
15
19
  }
16
- const secrets = [reportToken, reportRobot, context.userStatus.jwt, (_a = context.userStatus.profile) == null ? void 0 : _a.token, (_b = context.userStatus.drive) == null ? void 0 : _b.fresh_token, context.passport].filter((value) => typeof value === "string" && value.length > 0);
20
+ const secrets = [reportToken, reportRobot, context.userStatus.jwt, (_b = context.userStatus.profile) == null ? void 0 : _b.token, (_c = context.userStatus.drive) == null ? void 0 : _c.fresh_token, context.passport].filter((value) => typeof value === "string" && value.length > 0);
17
21
  const details = {
18
22
  time: (/* @__PURE__ */ new Date()).toISOString(),
19
23
  app_channel: context.productName,
20
24
  platform: "canva_addon",
21
25
  app_id: context.appId,
22
26
  app_version: String(context.version),
23
- sdk_version: "2.5.1",
24
- user_id: ((_c = context.userStatus.profile) == null ? void 0 : _c.id) ?? "unknown",
27
+ sdk_version: "2.6.0",
28
+ user_id: ((_d = context.userStatus.profile) == null ? void 0 : _d.id) ?? "unknown",
25
29
  platform_uid: context.userStatus.userId ?? "unknown",
26
30
  ...reportingPayload(params, secrets)
27
31
  };
@@ -0,0 +1,281 @@
1
+ import { cleanProps, cleanTimings, cleanDuration, cleanError } from "./sanitize.js";
2
+ const DEFAULT_TELEMETRY_ENDPOINT = "https://telemetry.imgkits.com/v1/events";
3
+ const namePattern = /^[a-z][a-z0-9_]{1,47}$/;
4
+ const idPattern = /^[A-Za-z0-9_.:-]{1,128}$/;
5
+ const BATCH_SIZE = 20;
6
+ const FLUSH_MS = 5e3;
7
+ const MAX_BODY_BYTES = 60 * 1024;
8
+ const MAX_QUEUE = 200;
9
+ const SESSION_LIMIT = 500;
10
+ const REQUEST_TIMEOUT_MS = 4e3;
11
+ const RETRY_DELAYS = [2e3, 6e3];
12
+ const DEDUPE_MS = 6e4;
13
+ function newId() {
14
+ var _a;
15
+ try {
16
+ if (typeof ((_a = globalThis.crypto) == null ? void 0 : _a.randomUUID) === "function") return globalThis.crypto.randomUUID();
17
+ } catch {
18
+ }
19
+ return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 12)}-${Math.random().toString(36).slice(2, 12)}`;
20
+ }
21
+ function isLocalPage() {
22
+ var _a;
23
+ try {
24
+ const host = (_a = globalThis.location) == null ? void 0 : _a.hostname;
25
+ return host === "localhost" || host === "127.0.0.1" || host === "[::1]" || host === "::1";
26
+ } catch {
27
+ return false;
28
+ }
29
+ }
30
+ function validEndpoint(raw) {
31
+ try {
32
+ const url = new URL(raw ?? DEFAULT_TELEMETRY_ENDPOINT);
33
+ const local = ["localhost", "127.0.0.1", "[::1]"].includes(url.hostname);
34
+ if (url.protocol !== "https:" && !(url.protocol === "http:" && local)) return null;
35
+ if (url.username || url.password || url.hash) return null;
36
+ return url.toString();
37
+ } catch {
38
+ return null;
39
+ }
40
+ }
41
+ function createTelemetry(getContext) {
42
+ let queue = [];
43
+ let timer = null;
44
+ let paused = false;
45
+ let sessionKey = "";
46
+ let seq = 0;
47
+ let accepted = 0;
48
+ let droppedBySessionLimit = 0;
49
+ let listening = false;
50
+ const inflight = /* @__PURE__ */ new Set();
51
+ const dedupe = /* @__PURE__ */ new Map();
52
+ const onVisibility = () => {
53
+ var _a;
54
+ try {
55
+ if (((_a = globalThis.document) == null ? void 0 : _a.visibilityState) === "hidden") flush(true);
56
+ } catch {
57
+ }
58
+ };
59
+ const onPageHide = () => flush(true);
60
+ const listen = () => {
61
+ var _a, _b, _c;
62
+ if (listening) return;
63
+ try {
64
+ (_b = (_a = globalThis.document) == null ? void 0 : _a.addEventListener) == null ? void 0 : _b.call(_a, "visibilitychange", onVisibility);
65
+ (_c = globalThis.addEventListener) == null ? void 0 : _c.call(globalThis, "pagehide", onPageHide);
66
+ listening = true;
67
+ } catch {
68
+ }
69
+ };
70
+ const unlisten = () => {
71
+ var _a, _b, _c;
72
+ if (!listening) return;
73
+ try {
74
+ (_b = (_a = globalThis.document) == null ? void 0 : _a.removeEventListener) == null ? void 0 : _b.call(_a, "visibilitychange", onVisibility);
75
+ (_c = globalThis.removeEventListener) == null ? void 0 : _c.call(globalThis, "pagehide", onPageHide);
76
+ } catch {
77
+ }
78
+ listening = false;
79
+ };
80
+ const schedule = () => {
81
+ if (timer || paused) return;
82
+ timer = setTimeout(() => {
83
+ timer = null;
84
+ flush(false);
85
+ }, FLUSH_MS);
86
+ };
87
+ const enqueue = (event) => {
88
+ if (paused) return;
89
+ if (accepted >= SESSION_LIMIT) {
90
+ droppedBySessionLimit++;
91
+ return;
92
+ }
93
+ accepted++;
94
+ queue.push(event);
95
+ if (queue.length > MAX_QUEUE) {
96
+ const index = queue.findIndex((item) => !item.error);
97
+ queue.splice(index >= 0 ? index : 0, 1);
98
+ }
99
+ listen();
100
+ if (queue.length >= BATCH_SIZE) flush(false);
101
+ else schedule();
102
+ };
103
+ const build = (mapped, context) => {
104
+ const { params } = mapped;
105
+ if (!params || typeof params.name !== "string" || !namePattern.test(params.name)) return null;
106
+ const scope = `${context.appId}|${context.productName}|${context.sessionId}`;
107
+ if (scope !== sessionKey) {
108
+ sessionKey = scope;
109
+ seq = 0;
110
+ }
111
+ const { props, dropped } = cleanProps(params.props, context.secrets);
112
+ const env = mapped.envOverride ?? (context.testMode || isLocalPage() ? "dev" : context.inReview ? "review" : "production");
113
+ const event = {
114
+ schema: "canva.v1",
115
+ event_id: newId(),
116
+ occurred_at: (/* @__PURE__ */ new Date()).toISOString(),
117
+ seq: ++seq,
118
+ app: { id: context.appId, channel: context.productName, version: String(context.version), sdk: "2.6.0" },
119
+ user: { id: context.userId && idPattern.test(context.userId) ? context.userId : null, plan: context.plan },
120
+ session: { id: context.sessionId, locale: context.locale },
121
+ env,
122
+ name: params.name,
123
+ flow: typeof params.flow === "string" && /^[a-z][a-z0-9_]{0,39}$/.test(params.flow) ? params.flow : "main",
124
+ props,
125
+ repeat_count: 1,
126
+ dropped_props: dropped
127
+ };
128
+ if (typeof params.operation_id === "string" && idPattern.test(params.operation_id)) event.operation_id = params.operation_id;
129
+ if (typeof params.page === "string" && /^[a-z][a-z0-9_]{0,39}$/.test(params.page)) event.page = params.page;
130
+ const timings = cleanTimings(params.timings);
131
+ if (timings) event.timings = timings;
132
+ const duration = cleanDuration(params.duration_ms);
133
+ if (duration !== void 0) event.duration_ms = duration;
134
+ if (params.error) event.error = cleanError(params.error, context.secrets);
135
+ return event;
136
+ };
137
+ const capture = (mapped) => {
138
+ var _a;
139
+ try {
140
+ if (paused) return;
141
+ const context = getContext();
142
+ if (context.reportingDisabled || ((_a = context.config) == null ? void 0 : _a.enabled) !== true || !validEndpoint(context.config.endpoint)) return;
143
+ const event = build(mapped, context);
144
+ if (!event) return;
145
+ if (event.error) {
146
+ const key = [event.name, event.error.code, event.error.stage, event.operation_id ?? ""].join("|");
147
+ const existing = dedupe.get(key);
148
+ if (existing) {
149
+ if (queue.includes(existing.event)) existing.event.repeat_count++;
150
+ else existing.extra++;
151
+ return;
152
+ }
153
+ const entry = {
154
+ event,
155
+ extra: 0,
156
+ timer: setTimeout(() => {
157
+ dedupe.delete(key);
158
+ if (entry.extra > 0) enqueue({ ...entry.event, event_id: newId(), occurred_at: (/* @__PURE__ */ new Date()).toISOString(), repeat_count: entry.extra });
159
+ }, DEDUPE_MS)
160
+ };
161
+ dedupe.set(key, entry);
162
+ }
163
+ enqueue(event);
164
+ } catch {
165
+ }
166
+ };
167
+ const send = (batch, unloading, attempt) => {
168
+ var _a;
169
+ const context = (() => {
170
+ try {
171
+ return getContext();
172
+ } catch {
173
+ return null;
174
+ }
175
+ })();
176
+ const endpoint = validEndpoint((_a = context == null ? void 0 : context.config) == null ? void 0 : _a.endpoint);
177
+ if (!endpoint || paused) return;
178
+ const controller = new AbortController();
179
+ inflight.add(controller);
180
+ const timeout = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS);
181
+ let request;
182
+ try {
183
+ request = fetch(endpoint, {
184
+ method: "POST",
185
+ headers: { "Content-Type": "application/json" },
186
+ body: JSON.stringify({ schema: "canva.v1", events: batch }),
187
+ credentials: "omit",
188
+ redirect: "error",
189
+ referrerPolicy: "no-referrer",
190
+ cache: "no-store",
191
+ mode: "cors",
192
+ keepalive: unloading,
193
+ signal: controller.signal
194
+ });
195
+ } catch {
196
+ clearTimeout(timeout);
197
+ inflight.delete(controller);
198
+ return;
199
+ }
200
+ const retry = () => {
201
+ if (unloading || paused || attempt >= RETRY_DELAYS.length) return;
202
+ setTimeout(() => send(batch, false, attempt + 1), RETRY_DELAYS[attempt]);
203
+ };
204
+ request.then(async (response) => {
205
+ if (response.status === 503) {
206
+ pause();
207
+ return;
208
+ }
209
+ if (response.ok) {
210
+ let body = null;
211
+ try {
212
+ body = await response.json();
213
+ } catch {
214
+ }
215
+ const seconds = body && typeof body === "object" ? body.pause_seconds : void 0;
216
+ if (typeof seconds === "number" && seconds > 0) pause();
217
+ return;
218
+ }
219
+ if (response.status === 429 || response.status >= 500) retry();
220
+ }, () => retry()).catch(() => {
221
+ }).finally(() => {
222
+ clearTimeout(timeout);
223
+ inflight.delete(controller);
224
+ });
225
+ };
226
+ const pause = () => {
227
+ paused = true;
228
+ queue = [];
229
+ if (timer) {
230
+ clearTimeout(timer);
231
+ timer = null;
232
+ }
233
+ };
234
+ const flush = (unloading = false) => {
235
+ try {
236
+ if (timer) {
237
+ clearTimeout(timer);
238
+ timer = null;
239
+ }
240
+ if (paused || !queue.length) return;
241
+ const pending = queue;
242
+ queue = [];
243
+ let batch = [];
244
+ let bytes = 64;
245
+ const encoder = new TextEncoder();
246
+ for (const event of pending) {
247
+ const size = encoder.encode(JSON.stringify(event)).length + 1;
248
+ if (size > MAX_BODY_BYTES) continue;
249
+ if (batch.length && (batch.length >= BATCH_SIZE || bytes + size > MAX_BODY_BYTES)) {
250
+ send(batch, unloading, 0);
251
+ batch = [];
252
+ bytes = 64;
253
+ }
254
+ batch.push(event);
255
+ bytes += size;
256
+ }
257
+ if (batch.length) send(batch, unloading, 0);
258
+ } catch {
259
+ }
260
+ };
261
+ const shutdown = () => {
262
+ try {
263
+ for (const [, entry] of dedupe) clearTimeout(entry.timer);
264
+ dedupe.clear();
265
+ if (droppedBySessionLimit > 0 && !paused) {
266
+ const context = getContext();
267
+ const event = build({ params: { name: "telemetry_dropped", props: { count: droppedBySessionLimit } } }, context);
268
+ if (event) queue.push(event);
269
+ droppedBySessionLimit = 0;
270
+ }
271
+ flush(true);
272
+ } catch {
273
+ }
274
+ unlisten();
275
+ };
276
+ return { capture, flush, shutdown };
277
+ }
278
+ export {
279
+ DEFAULT_TELEMETRY_ENDPOINT,
280
+ createTelemetry
281
+ };
@@ -0,0 +1,68 @@
1
+ import { isReportStage } from "./stage.js";
2
+ const namePattern = /^[a-z][a-z0-9_]{1,47}$/;
3
+ const idPattern = /^[A-Za-z0-9_.:-]{1,128}$/;
4
+ const pagePattern = /^[a-z][a-z0-9_]{0,39}$/;
5
+ const asId = (value) => typeof value === "string" && idPattern.test(value) ? value : void 0;
6
+ function mapUsage(params) {
7
+ const name = params.sum_key;
8
+ if (typeof name !== "string" || !namePattern.test(name) || name === "generate_retry") return null;
9
+ const data = params.data && typeof params.data === "object" && !Array.isArray(params.data) ? { ...params.data } : {};
10
+ const operation_id = asId(data.operation_id);
11
+ const page = typeof data.page === "string" && pagePattern.test(data.page) ? data.page : void 0;
12
+ const duration_ms = data.duration_ms;
13
+ const envOverride = data.mode === "demo" ? "dev" : void 0;
14
+ for (const key of ["operation_id", "page", "duration_ms", "mode", "session_id", "app_version", "platform", "occurred_at"]) delete data[key];
15
+ let error = params.error;
16
+ let mappedName = name;
17
+ if ((name === "login_fail" || name === "account_fail") && !error) {
18
+ const code = typeof data.error_code === "string" ? data.error_code : void 0;
19
+ error = { stage: "account", expected: false, code: code && /^[a-z][a-z0-9_]{1,63}$/.test(code) ? code.toUpperCase() : "ACCOUNT_FAILED" };
20
+ if (typeof data.stage === "string") data.account_stage = data.stage;
21
+ delete data.stage;
22
+ delete data.error_code;
23
+ }
24
+ if (name === "generate_fail" && (error == null ? void 0 : error.code) === "POLICY_BLOCKED") {
25
+ mappedName = "generate_blocked";
26
+ data.reason = "policy";
27
+ data.stage = error.stage;
28
+ }
29
+ return {
30
+ params: {
31
+ name: mappedName,
32
+ operation_id,
33
+ page,
34
+ flow: typeof params.flow === "string" ? params.flow : void 0,
35
+ props: data,
36
+ timings: params.timings,
37
+ duration_ms: typeof duration_ms === "number" ? duration_ms : void 0,
38
+ error
39
+ },
40
+ envOverride
41
+ };
42
+ }
43
+ function mapError(params) {
44
+ var _a, _b, _c;
45
+ const context = params.context && typeof params.context === "object" ? { ...params.context } : {};
46
+ const operation_id = asId(context.operation_id);
47
+ const contextCode = typeof context.error_code === "string" && /^[A-Z][A-Z0-9_]{1,63}$/.test(context.error_code) ? context.error_code : void 0;
48
+ delete context.operation_id;
49
+ delete context.error_code;
50
+ const props = { ...context, source: params.source ?? "ui" };
51
+ const stage = isReportStage(params.stage) ? params.stage : "unknown";
52
+ if (stage === "unknown" && typeof params.stage === "string") props.legacy_stage = params.stage.slice(0, 64);
53
+ if (((_a = params.api) == null ? void 0 : _a.status) !== void 0 && props.http_status === void 0) props.http_status = params.api.status;
54
+ if (((_b = params.api) == null ? void 0 : _b.response_code) !== void 0) props.backend_code = String(params.api.response_code).slice(0, 64);
55
+ if (typeof ((_c = params.api) == null ? void 0 : _c.request_id) === "string") props.request_id = params.api.request_id;
56
+ return {
57
+ params: {
58
+ name: "app_error",
59
+ operation_id,
60
+ props,
61
+ error: { stage, expected: false, code: contextCode, cause: params.error }
62
+ }
63
+ };
64
+ }
65
+ export {
66
+ mapError,
67
+ mapUsage
68
+ };
@@ -0,0 +1,97 @@
1
+ import { isAbortError, ApiError } from "../error.js";
2
+ import { usageReportingText } from "../usage_reporting_payload.js";
3
+ import { isReportStage, StageError, toErrorCode } from "./stage.js";
4
+ const keyPattern = /^[a-z][a-z0-9_]{0,39}$/;
5
+ const sensitiveSegments = /* @__PURE__ */ new Set([
6
+ "prompt",
7
+ "text",
8
+ "content",
9
+ "message",
10
+ "url",
11
+ "uri",
12
+ "link",
13
+ "href",
14
+ "token",
15
+ "jwt",
16
+ "passport",
17
+ "authorization",
18
+ "cookie",
19
+ "password",
20
+ "secret",
21
+ "credential",
22
+ "email",
23
+ "stack",
24
+ "body",
25
+ "html"
26
+ ]);
27
+ const sensitiveKeys = /* @__PURE__ */ new Set(["input", "output", "result", "file", "filename", "file_name", "image", "audio", "video", "data"]);
28
+ const MAX_PROPS = 20;
29
+ const MAX_DURATION = 30 * 24 * 60 * 60 * 1e3;
30
+ function isSensitiveKey(key) {
31
+ return sensitiveKeys.has(key) || key.split("_").some((segment) => sensitiveSegments.has(segment));
32
+ }
33
+ function cleanProps(input, secrets) {
34
+ const props = {};
35
+ let dropped = 0;
36
+ if (input === null || typeof input !== "object" || Array.isArray(input)) return { props, dropped };
37
+ for (const [key, descriptor] of Object.entries(Object.getOwnPropertyDescriptors(input))) {
38
+ if (!descriptor.enumerable || !("value" in descriptor)) continue;
39
+ const value = descriptor.value;
40
+ if (Object.keys(props).length >= MAX_PROPS || !keyPattern.test(key) || isSensitiveKey(key)) {
41
+ dropped++;
42
+ continue;
43
+ }
44
+ if (value === null || typeof value === "boolean") props[key] = value;
45
+ else if (typeof value === "number" && Number.isFinite(value)) props[key] = value;
46
+ else if (typeof value === "string") {
47
+ const clean = usageReportingText(value, 128, secrets);
48
+ if (clean.includes("[redacted]") || clean !== value.slice(0, clean.length)) dropped++;
49
+ else props[key] = clean;
50
+ } else dropped++;
51
+ }
52
+ return { props, dropped };
53
+ }
54
+ function cleanTimings(input) {
55
+ if (input === null || typeof input !== "object" || Array.isArray(input)) return void 0;
56
+ const timings = {};
57
+ for (const [key, value] of Object.entries(input)) {
58
+ if (isReportStage(key) && typeof value === "number" && Number.isFinite(value) && value >= 0 && value <= MAX_DURATION) {
59
+ timings[key] = Math.round(value);
60
+ }
61
+ }
62
+ return Object.keys(timings).length ? timings : void 0;
63
+ }
64
+ function cleanDuration(value) {
65
+ return typeof value === "number" && Number.isFinite(value) && value >= 0 && value <= MAX_DURATION ? Math.round(value) : void 0;
66
+ }
67
+ const expectedCodes = /* @__PURE__ */ new Set(["ABORTED", "POLICY_BLOCKED", "NOT_FOUND", "USER_OFFLINE", "PERMISSION_DENIED"]);
68
+ function cleanError(input, secrets) {
69
+ var _a;
70
+ const stage = isReportStage(input.stage) ? input.stage : "unknown";
71
+ const cause = input.cause instanceof StageError ? input.cause.cause : input.cause;
72
+ const code = typeof input.code === "string" && /^[A-Z][A-Z0-9_]{1,63}$/.test(input.code) ? input.code : input.cause instanceof StageError ? input.cause.code : toErrorCode(cause, stage);
73
+ const stageExpected = input.cause instanceof StageError ? input.cause.expected : void 0;
74
+ const expected = input.expected ?? stageExpected ?? (isAbortError(cause) || expectedCodes.has(code));
75
+ const payload = { code, stage, expected };
76
+ const fields = cause !== null && typeof cause === "object" ? cause : void 0;
77
+ if (typeof (fields == null ? void 0 : fields.name) === "string") payload.name = usageReportingText(fields.name, 128, secrets);
78
+ const message = typeof cause === "string" ? cause : typeof (fields == null ? void 0 : fields.message) === "string" ? fields.message : void 0;
79
+ if (message) payload.message = usageReportingText(message, 500, secrets);
80
+ if (!expected && typeof (fields == null ? void 0 : fields.stack) === "string") {
81
+ payload.stack = Array.from(fields.stack.split("\n").slice(0, 40).map((line) => usageReportingText(line, 300, secrets)).join("\n")).slice(0, 4096).join("");
82
+ }
83
+ if (cause instanceof ApiError) {
84
+ if (cause.status !== void 0) payload.http_status = cause.status;
85
+ if (typeof cause.code === "number") payload.backend_code = String(cause.code);
86
+ const requestId = (_a = cause.data) == null ? void 0 : _a.request_id;
87
+ if (typeof requestId === "string") payload.request_id = usageReportingText(requestId, 128, secrets);
88
+ }
89
+ return payload;
90
+ }
91
+ export {
92
+ cleanDuration,
93
+ cleanError,
94
+ cleanProps,
95
+ cleanTimings,
96
+ isSensitiveKey
97
+ };
@@ -0,0 +1,71 @@
1
+ import { isAbortError, ApiError } from "../error.js";
2
+ const REPORT_STAGES = [
3
+ "input_read",
4
+ "selection_read",
5
+ "upload",
6
+ "text_check",
7
+ "content_extract",
8
+ "chat",
9
+ "create_prediction",
10
+ "wait_prediction",
11
+ "cancel_prediction",
12
+ "tts",
13
+ "vtt",
14
+ "direct_api",
15
+ "parse_result",
16
+ "download_result",
17
+ "local_render",
18
+ "insert",
19
+ "consume",
20
+ "render",
21
+ "account",
22
+ "unknown"
23
+ ];
24
+ function isReportStage(value) {
25
+ return typeof value === "string" && REPORT_STAGES.includes(value);
26
+ }
27
+ const errorCodePattern = /^[A-Z][A-Z0-9_]{1,63}$/;
28
+ class StageError extends Error {
29
+ constructor(cause, options) {
30
+ super(cause instanceof Error ? cause.message : typeof cause === "string" ? cause : "Stage failed.");
31
+ this.name = "StageError";
32
+ this.stage = options.stage;
33
+ this.code = options.code !== void 0 && errorCodePattern.test(options.code) ? options.code : toErrorCode(cause, options.stage);
34
+ this.expected = options.expected;
35
+ this.cause = cause;
36
+ }
37
+ }
38
+ function toErrorCode(error, stage) {
39
+ if (error instanceof StageError) return error.code;
40
+ if (isAbortError(error)) return "ABORTED";
41
+ const code = error instanceof ApiError ? error.code : error !== null && typeof error === "object" && "code" in error ? error.code : void 0;
42
+ if (typeof code === "string" && /^[a-z][a-z0-9_]{1,63}$/.test(code)) return code.toUpperCase();
43
+ if (typeof code === "string" && errorCodePattern.test(code)) return code;
44
+ if (stage && stage !== "unknown") return `${stage.toUpperCase()}_FAILED`;
45
+ return "UNKNOWN";
46
+ }
47
+ function createStageTimer(now = () => Date.now()) {
48
+ const timings = {};
49
+ const add = (stage, ms) => {
50
+ timings[stage] = (timings[stage] ?? 0) + Math.max(0, Math.round(ms));
51
+ };
52
+ return {
53
+ timings,
54
+ async run(stage, task) {
55
+ const startedAt = now();
56
+ try {
57
+ return await task();
58
+ } finally {
59
+ add(stage, now() - startedAt);
60
+ }
61
+ },
62
+ add
63
+ };
64
+ }
65
+ export {
66
+ REPORT_STAGES,
67
+ StageError,
68
+ createStageTimer,
69
+ isReportStage,
70
+ toErrorCode
71
+ };
@@ -5,25 +5,29 @@ import { usageReportingData, usageReportingText } from "./usage_reporting_payloa
5
5
  function createUsageReportingApi(getContext) {
6
6
  return {
7
7
  async reportUsage(params, options = {}) {
8
- var _a, _b, _c, _d, _e;
8
+ var _a, _b, _c, _d, _e, _f;
9
9
  try {
10
10
  const context = getContext();
11
11
  const config = context.usageReporting ?? {};
12
12
  if (config.enabled === false || ((_a = options.signal) == null ? void 0 : _a.aborted)) return false;
13
13
  if (config.enabled !== void 0 && typeof config.enabled !== "boolean") return false;
14
- if (!params || typeof params !== "object" || Array.isArray(params) || Object.keys(params).some((key) => !["sum_key", "title", "data"].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;
14
+ try {
15
+ if (params && typeof params === "object") (_b = context.capture) == null ? void 0 : _b.call(context, params);
16
+ } catch {
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;
15
19
  const appKey = config.appKey ?? `${context.productName}_canva`;
16
20
  if (typeof appKey !== "string" || !/^[a-zA-Z0-9_.:-]{1,128}$/.test(appKey)) return false;
17
21
  const timeoutMs = options.timeoutMs ?? 4e3;
18
22
  if (!Number.isInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > 4e3) return false;
19
23
  const url = new URL(config.endpoint ?? "https://log.aibabygenerator.io/api/report");
20
24
  if (url.protocol !== "https:" && !(url.protocol === "http:" && ["localhost", "127.0.0.1", "[::1]"].includes(url.hostname)) || url.username || url.password || url.search || url.hash) return false;
21
- const secrets = [context.userStatus.jwt, (_b = context.userStatus.profile) == null ? void 0 : _b.token, (_c = context.userStatus.drive) == null ? void 0 : _c.fresh_token, ...context.secrets ?? []].filter((value) => typeof value === "string" && value.length > 0);
25
+ const secrets = [context.userStatus.jwt, (_c = context.userStatus.profile) == null ? void 0 : _c.token, (_d = context.userStatus.drive) == null ? void 0 : _d.fresh_token, ...context.secrets ?? []].filter((value) => typeof value === "string" && value.length > 0);
22
26
  const occurredAt = (/* @__PURE__ */ new Date()).toISOString();
23
27
  const base = usageReportingData({ ...context.metadata, occurred_at: occurredAt }, secrets);
24
28
  const attributes = usageReportingData(params.data, secrets);
25
29
  const data = usageReportingData({ ...base, ...Object.fromEntries(Object.entries(attributes).filter(([key]) => !(key in base))) }, secrets);
26
- const userId = (_d = context.userStatus.profile) == null ? void 0 : _d.id;
30
+ const userId = (_e = context.userStatus.profile) == null ? void 0 : _e.id;
27
31
  if (userId !== void 0 && (typeof userId !== "string" || userId.length > 128)) return false;
28
32
  const title = usageReportingText(params.title, 128, secrets);
29
33
  url.searchParams.set("app_key", appKey);
@@ -45,7 +49,7 @@ function createUsageReportingApi(getContext) {
45
49
  if (url.href.length > 8192) return false;
46
50
  const requestUrl = url.toString();
47
51
  for (let attempt = 0; attempt < 2; attempt++) {
48
- if ((_e = options.signal) == null ? void 0 : _e.aborted) return false;
52
+ if ((_f = options.signal) == null ? void 0 : _f.aborted) return false;
49
53
  try {
50
54
  const response = await withRequest({ signal: options.signal, timeoutMs }, (signal) => fetch(requestUrl, {
51
55
  method: "GET",
package/dist/index.js CHANGED
@@ -3,11 +3,17 @@ import { YiChongCanvaContext } from "./login/context.js";
3
3
  import { useYiChongCanva } from "./login/use_canva.js";
4
4
  import { ApiError, isAbortError } from "./api/error.js";
5
5
  import { getPredictionOutputUrl } from "./api/predictions.js";
6
+ import { REPORT_STAGES, StageError, createStageTimer, isReportStage, toErrorCode } from "./api/telemetry/stage.js";
6
7
  export {
7
8
  ApiError,
9
+ REPORT_STAGES,
10
+ StageError,
8
11
  YiChongCanvaContext,
9
12
  YiChongCanvaProvider,
13
+ createStageTimer,
10
14
  getPredictionOutputUrl,
11
15
  isAbortError,
16
+ isReportStage,
17
+ toErrorCode,
12
18
  useYiChongCanva
13
19
  };
@@ -73,6 +73,8 @@ const YiChongCanvaContext = React.createContext(
73
73
  throw new ApiError("Wrap your components in YiChongCanvaProvider first.", "provider_missing");
74
74
  },
75
75
  reportUsage: async () => false,
76
+ track: () => {
77
+ },
76
78
  reduceFreeCnt: async () => {
77
79
  throw new ApiError("Wrap your components in YiChongCanvaProvider first.", "provider_missing");
78
80
  },
@@ -14,6 +14,9 @@ import { createUsageApi } from "../api/usage.js";
14
14
  import { createUploadApi } from "../api/uploads.js";
15
15
  import { createErrorReportingApi } from "../api/reporting.js";
16
16
  import { createUsageReportingApi } from "../api/usage_reporting.js";
17
+ import { createTelemetry } from "../api/telemetry/client.js";
18
+ import { mapError, mapUsage } from "../api/telemetry/map_legacy.js";
19
+ import { language } from "../api/request.js";
17
20
  import { isValidUsageCount, invalidUsageResult, skippedUsage, recordUsage } from "./consumption.js";
18
21
  import { readCache, writeCache, versionCacheKey, testCacheKey } from "./cache.js";
19
22
  import { ApiError } from "../api/error.js";
@@ -41,6 +44,7 @@ const YiChongCanvaProvider = ({
41
44
  uploadBaseUrl = "https://ai.imgkits.com",
42
45
  getLocale,
43
46
  usageReporting,
47
+ telemetry: telemetryConfig,
44
48
  autoLogin = true,
45
49
  testMode: _testMode = "noTest",
46
50
  version = 1,
@@ -135,9 +139,37 @@ const YiChongCanvaProvider = ({
135
139
  var _a;
136
140
  return {
137
141
  ...getApiContext(),
138
- passport: (_a = passportRef.current) == null ? void 0 : _a.passport
142
+ passport: (_a = passportRef.current) == null ? void 0 : _a.passport,
143
+ capture: (params) => telemetry.capture(mapError(params))
139
144
  };
140
145
  }));
146
+ const telemetryConfigRef = useRef(telemetryConfig);
147
+ telemetryConfigRef.current = telemetryConfig;
148
+ const telemetryPlanRef = useRef(() => "unknown");
149
+ const [telemetry] = useState(() => createTelemetry(() => {
150
+ var _a, _b, _c, _d, _e;
151
+ const context = getApiContext();
152
+ const scope = `${context.appId}|${context.productName}`;
153
+ const status = identityScopeRef.current === scope ? context.userStatus : {};
154
+ return {
155
+ config: telemetryConfigRef.current,
156
+ reportingDisabled: ((_a = context.usageReporting) == null ? void 0 : _a.enabled) === false,
157
+ appId: context.appId,
158
+ productName: context.productName,
159
+ version: context.version,
160
+ userId: (_b = status.profile) == null ? void 0 : _b.id,
161
+ plan: status.profile ? telemetryPlanRef.current() : "unknown",
162
+ sessionId: ((_c = usageSessionRef.current) == null ? void 0 : _c.id) ?? "",
163
+ locale: language(context.getLocale),
164
+ inReview: isInTestRef.current,
165
+ testMode: testRef.current !== "noTest",
166
+ secrets: [status.jwt, (_d = status.profile) == null ? void 0 : _d.token, (_e = passportRef.current) == null ? void 0 : _e.passport].filter((value) => !!value)
167
+ };
168
+ }));
169
+ const captureUsage = (params) => {
170
+ const mapped = mapUsage(params);
171
+ if (mapped) telemetry.capture(mapped);
172
+ };
141
173
  const [usageReportingApi] = useState(() => createUsageReportingApi(() => {
142
174
  var _a, _b, _c;
143
175
  const context = getApiContext();
@@ -147,7 +179,8 @@ const YiChongCanvaProvider = ({
147
179
  // 子组件 effect 可能先于 Provider 的换应用 effect 执行,不能把旧用户算入新应用。
148
180
  userStatus: identityScopeRef.current === scope ? context.userStatus : {},
149
181
  metadata: { session_id: (_a = usageSessionRef.current) == null ? void 0 : _a.id, app_version: String(context.version), platform: "canva_addon" },
150
- secrets: [context.userStatus.jwt, (_b = context.userStatus.profile) == null ? void 0 : _b.token, (_c = passportRef.current) == null ? void 0 : _c.passport].filter((value) => !!value)
182
+ secrets: [context.userStatus.jwt, (_b = context.userStatus.profile) == null ? void 0 : _b.token, (_c = passportRef.current) == null ? void 0 : _c.passport].filter((value) => !!value),
183
+ capture: captureUsage
151
184
  };
152
185
  }));
153
186
  const reportAccountUsage = (sum_key, title, run, data = {}) => {
@@ -204,7 +237,13 @@ const YiChongCanvaProvider = ({
204
237
  var _a, _b;
205
238
  return ((_b = (_a = userStatusRef.current.profile) == null ? void 0 : _a.usage_limits) == null ? void 0 : _b.free_limit) === -1;
206
239
  };
207
- const [reportAccountFailure] = useState(() => createAccountReporter(errorReportingApi.reportError));
240
+ const [reportAccountFailure] = useState(() => createAccountReporter(createErrorReportingApi(() => {
241
+ var _a;
242
+ return {
243
+ ...getApiContext(),
244
+ passport: (_a = passportRef.current) == null ? void 0 : _a.passport
245
+ };
246
+ }).reportError));
208
247
  const beginAccountRun = (operation) => {
209
248
  var _a, _b;
210
249
  (_a = sessionStopRef.current) == null ? void 0 : _a.call(sessionStopRef, false);
@@ -410,6 +449,7 @@ const YiChongCanvaProvider = ({
410
449
  useEffect(() => {
411
450
  updateUserStatus({});
412
451
  }, [test]);
452
+ useEffect(() => () => telemetry.shutdown(), []);
413
453
  useEffect(() => {
414
454
  mountedRef.current = true;
415
455
  const scope = `${appId}|${productName}`;
@@ -595,7 +635,12 @@ const YiChongCanvaProvider = ({
595
635
  const detail = subscription == null ? void 0 : subscription.detail;
596
636
  return !!detail && (!detail.ends_at || new Date(detail.ends_at) > /* @__PURE__ */ new Date() || !!(team_subscription == null ? void 0 : team_subscription.detail));
597
637
  };
598
- const use = (cnt = 1, force = false, notUpload = false) => {
638
+ telemetryPlanRef.current = () => {
639
+ var _a, _b;
640
+ if (currentSubscribed()) return ((_b = (_a = userStatusRef.current.profile) == null ? void 0 : _a.usage_limits) == null ? void 0 : _b.monthly_usage_limit) === -1 ? "unlimited" : "subscriber";
641
+ return isFreeUnlimited() ? "unlimited" : "free";
642
+ };
643
+ const use = (cnt = 1, force = false, notUpload = false, options) => {
599
644
  if (!isValidUsageCount(cnt)) return Promise.resolve(invalidUsageResult());
600
645
  const queue = getUsageQueue();
601
646
  const isCurrent = () => mountedRef.current && getUsageQueue() === queue;
@@ -645,6 +690,21 @@ const YiChongCanvaProvider = ({
645
690
  error: { code: "unexpected_error", message: "Usage recording could not be started." }
646
691
  }));
647
692
  queue.tail = pending;
693
+ void pending.then((result) => {
694
+ const code = "error" in result && result.error ? result.error.code : void 0;
695
+ const error = result.status === "failed" || result.status === "unknown" || result.status === "partial" && result.remaining !== "skipped" ? {
696
+ stage: "consume",
697
+ expected: false,
698
+ code: typeof code === "string" && /^[a-z][a-z0-9_]{1,63}$/.test(code) ? code.toUpperCase() : "CONSUME_FAILED"
699
+ } : void 0;
700
+ telemetry.capture({ params: {
701
+ name: "consume_result",
702
+ operation_id: options == null ? void 0 : options.operationId,
703
+ props: { status: result.status, cnt, ..."reason" in result && result.reason ? { reason: result.reason } : {} },
704
+ error
705
+ } });
706
+ }).catch(() => {
707
+ });
648
708
  return pending;
649
709
  };
650
710
  const canUse = (cnt = 1, force = false) => {
@@ -733,6 +793,12 @@ const YiChongCanvaProvider = ({
733
793
  ...uploadApi,
734
794
  ...errorReportingApi,
735
795
  ...usageReportingApi,
796
+ track: (params) => {
797
+ try {
798
+ telemetry.capture({ params });
799
+ } catch {
800
+ }
801
+ },
736
802
  userStatus,
737
803
  updateUserStatus,
738
804
  handleLogin: login,
@@ -5,4 +5,5 @@
5
5
  */
6
6
  export { ApiError, isAbortError } from './error';
7
7
  export { getPredictionOutputUrl } from './predictions';
8
- 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, UsageReportingApi, UsageReportingConfig, ReportErrorResult, PresignedUrlResponse, TextModerationApi, TextModerationCategory, TextModerationDecision, TextModerationResult, UploadApi, UploadFileParams, UploadFileResult, UploadedPart, UploadPartUrlResponse, UploadProgress, UsageApi, UsageParams, UsageResponse, } from './types';
8
+ 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';
@@ -1,11 +1,13 @@
1
1
  import { ApiContext } from './request';
2
- import { ErrorReportingApi } from './types';
2
+ import { ErrorReportingApi, ReportErrorParams } from './types';
3
3
  /** 上报的应用/账号归属由 Provider 注入;passport 只参与脱敏,不会作为上报认证票据。 */
4
4
  export interface ReportingContext extends Pick<ApiContext, "userStatus" | "productName"> {
5
5
  appId: string;
6
6
  version: number;
7
7
  /** 只用于从诊断内容中移除当前账户凭据。 */
8
8
  passport?: string;
9
+ /** 2.6.0:把同一次调用登记到新通道(app_error)。同步、不抛错,不改变下面旧上报的结果或异常。 */
10
+ capture?: (params: ReportErrorParams) => void;
9
11
  }
10
12
  /**
11
13
  * 绑定显式错误上报能力:整理诊断信息,交由现有 Worker 转发到指定飞书机器人。
@@ -0,0 +1,34 @@
1
+ import { MappedEvent } from './map_legacy';
2
+ import { TelemetryConfig, TelemetryEvent } from './types';
3
+ export declare const DEFAULT_TELEMETRY_ENDPOINT = "https://telemetry.imgkits.com/v1/events";
4
+ /** Provider 在每次 capture 时提供的最新快照;任何字段读取失败都只丢弃本条事件。 */
5
+ export interface TelemetryContext {
6
+ config?: TelemetryConfig;
7
+ /** usageReporting.enabled === false 时两条通道都关闭。 */
8
+ reportingDisabled: boolean;
9
+ appId: string;
10
+ productName: string;
11
+ version: number;
12
+ userId?: string;
13
+ plan: TelemetryEvent["user"]["plan"];
14
+ sessionId: string;
15
+ locale: string;
16
+ inReview: boolean;
17
+ testMode: boolean;
18
+ secrets: readonly string[];
19
+ }
20
+ export interface TelemetryClient {
21
+ /** 同步登记一条事件,永不抛错、不返回 Promise;新通道关闭时直接忽略。 */
22
+ capture(event: MappedEvent): void;
23
+ /** 立即发送队列;unloading=true 时使用 keepalive。 */
24
+ flush(unloading?: boolean): void;
25
+ /** Provider 卸载:发送剩余事件并移除监听。 */
26
+ shutdown(): void;
27
+ }
28
+ /**
29
+ * 新通道客户端。设计见 02-SDK上报层.md 第 6 节:
30
+ * 内存队列,满 20 条或 5 秒发送;页面隐藏时 keepalive;只对网络/超时/429/5xx 重试两次;
31
+ * 服务端返回 pause_seconds 或 503 时本会话停止;每会话最多 500 条;同一错误 60 秒内合并计数。
32
+ * 不读写本地存储,不调用 reportError,任何异常都在内部吞掉。
33
+ */
34
+ export declare function createTelemetry(getContext: () => TelemetryContext): TelemetryClient;
@@ -0,0 +1,2 @@
1
+ export { StageError, toErrorCode, createStageTimer, isReportStage, REPORT_STAGES } from './stage';
2
+ export type { ReportStage, TelemetryConfig, TelemetryErrorInput, TelemetryEvent, TelemetryErrorPayload, TelemetryProps, TelemetryTimings, TrackParams, } from './types';
@@ -0,0 +1,14 @@
1
+ import { TrackParams } from './types';
2
+ import { ReportErrorParams, ReportUsageParams } from '../types';
3
+ /** 映射结果;envOverride 用于把模板本地演示(mode: demo)记为 dev。 */
4
+ export interface MappedEvent {
5
+ params: TrackParams;
6
+ envOverride?: "dev";
7
+ }
8
+ /**
9
+ * reportUsage → 新通道事件(01 第 7.1 节)。返回 null 表示该事件不进新通道。
10
+ * 只读取参数,不修改;旧通道的发送内容不受映射影响。
11
+ */
12
+ export declare function mapUsage(params: ReportUsageParams): MappedEvent | null;
13
+ /** reportError → 新通道 app_error(01 第 7.2 节)。调用 reportError 即表示需要关注,expected 恒为 false。 */
14
+ export declare function mapError(params: ReportErrorParams): MappedEvent;
@@ -0,0 +1,11 @@
1
+ import { TelemetryErrorInput, TelemetryErrorPayload, TelemetryProps, TelemetryTimings } from './types';
2
+ export declare function isSensitiveKey(key: string): boolean;
3
+ /** 只保留扁平的基本类型;敏感键和被脱敏改动过的字符串整键丢弃,并返回丢弃数量。 */
4
+ export declare function cleanProps(input: unknown, secrets: readonly string[]): {
5
+ props: TelemetryProps;
6
+ dropped: number;
7
+ };
8
+ export declare function cleanTimings(input: unknown): TelemetryTimings | undefined;
9
+ export declare function cleanDuration(value: unknown): number | undefined;
10
+ /** 从应用传入的错误描述生成上报对象;stack 只在 expected=false 时保留。 */
11
+ export declare function cleanError(input: TelemetryErrorInput, secrets: readonly string[]): TelemetryErrorPayload;
@@ -0,0 +1,33 @@
1
+ import { ReportStage } from './types';
2
+ /** stage 词表,与 01-事件格式.md 第 4.2 节一致。 */
3
+ export declare const REPORT_STAGES: readonly ReportStage[];
4
+ export declare function isReportStage(value: unknown): value is ReportStage;
5
+ /**
6
+ * 携带失败步骤和错误码的错误,供生成流程抛给 app.tsx 记录 generate_fail。
7
+ * 只是数据载体,不上报、不重试;cause 保留原始错误,isAbortError(cause) 仍可识别取消。
8
+ */
9
+ export declare class StageError extends Error {
10
+ readonly stage: ReportStage;
11
+ readonly code: string;
12
+ readonly expected?: boolean;
13
+ readonly cause: unknown;
14
+ constructor(cause: unknown, options: {
15
+ stage: ReportStage;
16
+ code?: string;
17
+ expected?: boolean;
18
+ });
19
+ }
20
+ /**
21
+ * 按 01 第 5 节的顺序推断错误码:StageError → SDK / Canva 的字符串错误码转大写 → <STAGE>_FAILED → UNKNOWN。
22
+ * 数字业务码不当作错误码(放 backend_code),避免后端自由文本进入分组键。
23
+ */
24
+ export declare function toErrorCode(error: unknown, stage?: ReportStage): string;
25
+ /**
26
+ * 记录每一步耗时:timer.run("upload", () => client.uploadFile(...))。
27
+ * 失败的步骤同样记录耗时;同一步骤多次执行时累加。只计时,不改变返回值或异常。
28
+ */
29
+ export declare function createStageTimer(now?: () => number): {
30
+ timings: Partial<Record<ReportStage, number>>;
31
+ run<T>(stage: ReportStage, task: () => Promise<T> | T): Promise<T>;
32
+ add: (stage: ReportStage, ms: number) => void;
33
+ };
@@ -0,0 +1,86 @@
1
+ /**
2
+ * 新通道(schema canva.v1)的公开类型。格式定义见 new_canva/docs/canva-telemetry/01-事件格式.md。
3
+ * 新通道与旧 GET 统计、飞书错误上报并行,默认关闭;这里的类型不改变旧接口的任何行为。
4
+ */
5
+ /** 失败、耗时所属的步骤;应用不另起名字,子流程用 flow 区分。 */
6
+ export type ReportStage = "input_read" | "selection_read" | "upload" | "text_check" | "content_extract" | "chat" | "create_prediction" | "wait_prediction" | "cancel_prediction" | "tts" | "vtt" | "direct_api" | "parse_result" | "download_result" | "local_render" | "insert" | "consume" | "render" | "account" | "unknown";
7
+ /** 扁平属性:只允许字符串、数字、布尔和 null。不放用户输入、提示词、URL、文件名或凭据。 */
8
+ export type TelemetryProps = Record<string, string | number | boolean | null>;
9
+ /** 每一步的耗时(毫秒),键只能取 ReportStage。 */
10
+ export type TelemetryTimings = Partial<Record<ReportStage, number>>;
11
+ /** 应用传入的错误描述;SDK 从 cause 提取 name / message / stack 并脱敏。 */
12
+ export interface TelemetryErrorInput {
13
+ /** 大写蛇形错误码;省略时按 toErrorCode(cause, stage) 推断。 */
14
+ code?: string;
15
+ /** 失败所在步骤。 */
16
+ stage: ReportStage;
17
+ /** 是否在预料之中;省略时 SDK 自动判断(取消、审核拦截、Canva not_found 等为 true,其余为 false)。 */
18
+ expected?: boolean;
19
+ /** 原始错误对象,可以是 Error、ApiError、StageError 或字符串。 */
20
+ cause?: unknown;
21
+ }
22
+ /** client.track 的参数:只进新通道。 */
23
+ export interface TrackParams {
24
+ /** 小写蛇形,"对象_动作",例如 quota_blocked、example_click。 */
25
+ name: string;
26
+ /** 同一次生成共用的操作 ID。 */
27
+ operation_id?: string;
28
+ /** 子流程名,默认 main。 */
29
+ flow?: string;
30
+ /** 当前页面:index / progress / result 或应用自定义页面名。 */
31
+ page?: string;
32
+ props?: TelemetryProps;
33
+ timings?: TelemetryTimings;
34
+ duration_ms?: number;
35
+ error?: TelemetryErrorInput;
36
+ }
37
+ /** Provider 的 telemetry 属性。 */
38
+ export interface TelemetryConfig {
39
+ /** 默认 false:不发送任何新通道请求,旧通道不受影响。 */
40
+ enabled?: boolean;
41
+ /** 默认 https://telemetry.imgkits.com/v1/events;只接受 https,本地调试允许 http://localhost。 */
42
+ endpoint?: string;
43
+ }
44
+ /** 发送到采集 Worker 的单条事件(信封 + 事件 + 错误)。 */
45
+ export interface TelemetryEvent {
46
+ schema: "canva.v1";
47
+ event_id: string;
48
+ occurred_at: string;
49
+ seq: number;
50
+ app: {
51
+ id: string;
52
+ channel: string;
53
+ version: string;
54
+ sdk: string;
55
+ };
56
+ user: {
57
+ id: string | null;
58
+ plan: "free" | "subscriber" | "unlimited" | "unknown";
59
+ };
60
+ session: {
61
+ id: string;
62
+ locale: string;
63
+ };
64
+ env: "production" | "review" | "dev";
65
+ name: string;
66
+ operation_id?: string;
67
+ flow: string;
68
+ page?: string;
69
+ props: TelemetryProps;
70
+ timings?: TelemetryTimings;
71
+ duration_ms?: number;
72
+ error?: TelemetryErrorPayload;
73
+ repeat_count: number;
74
+ dropped_props: number;
75
+ }
76
+ export interface TelemetryErrorPayload {
77
+ code: string;
78
+ stage: ReportStage;
79
+ expected: boolean;
80
+ name?: string;
81
+ message?: string;
82
+ stack?: string;
83
+ http_status?: number;
84
+ backend_code?: string;
85
+ request_id?: string;
86
+ }
@@ -1,9 +1,4 @@
1
- /**
2
- * 后端 API 的公开参数、响应与方法签名。
3
- * 在 YiChongCanvaProvider 子组件中用 useYiChongCanva() 获取 client,直接调用同名方法。
4
- * 身份、渠道、语言等公共信息由 Provider 提供,不需要业务额外封装一层转发 API。
5
- * 各服务保留自己的响应结构:AI 用 code,账户消费用 ok,上传和上报另有对应类型。
6
- */
1
+ import { TelemetryErrorInput, TelemetryTimings, TrackParams } from './telemetry/types';
7
2
  /** 可完整序列化的 JSON 值;运行时还会拒绝 NaN、Infinity、循环引用及类实例。 */
8
3
  export type JsonValue = string | number | boolean | null | JsonValue[] | JsonObject;
9
4
  /** 模型参数等开放对象;可选字段应省略,不要在对象内部放 undefined、File 或函数。 */
@@ -611,6 +606,20 @@ export interface ReportUsageParams {
611
606
  * 对象最多 3 层、30 个字段,数组最多 10 项,字符串最多 256 字符;最终 URL 最多 8192 字符。
612
607
  */
613
608
  data?: Record<string, unknown> | null;
609
+ /** 2.6.0 起,只进新通道(旧 GET 统计忽略):子流程名,默认 main。 */
610
+ flow?: string;
611
+ /** 2.6.0 起,只进新通道:每一步耗时(毫秒),键取 ReportStage。 */
612
+ timings?: TelemetryTimings;
613
+ /** 2.6.0 起,只进新通道:失败事件的错误描述。code 为 POLICY_BLOCKED 的 generate_fail 在新通道记为 generate_blocked。 */
614
+ error?: TelemetryErrorInput;
615
+ }
616
+ /** 新通道(canva.v1)专用的上报方法;默认关闭,见 Provider 的 telemetry 属性。 */
617
+ export interface TelemetryApi {
618
+ /**
619
+ * 只发到新通道:标准新增事件(如 quota_blocked)和应用自定义事件。
620
+ * 同步返回、永不抛错,不影响旧统计和飞书错误上报;新通道关闭时直接忽略。
621
+ */
622
+ track(params: TrackParams): void;
614
623
  }
615
624
  /** 行为统计,不扣费、不刷新账户、不弹错误,也不会把自身失败转发到飞书。 */
616
625
  export interface UsageReportingApi {
@@ -1,5 +1,5 @@
1
1
  import { CommonRequestContext } from './request';
2
- import { UsageReportingApi, UsageReportingConfig } from './types';
2
+ import { ReportUsageParams, UsageReportingApi, UsageReportingConfig } from './types';
3
3
  /** Provider 当前快照;账户尚未就绪也可调用,不通过登录校验或账户消费 API。 */
4
4
  export interface UsageReportingContext extends CommonRequestContext {
5
5
  usageReporting?: UsageReportingConfig;
@@ -7,6 +7,8 @@ export interface UsageReportingContext extends CommonRequestContext {
7
7
  metadata?: Record<string, unknown>;
8
8
  /** 已知凭据只参与脱敏,绝不发送至统计接口。 */
9
9
  secrets?: readonly string[];
10
+ /** 2.6.0:把同一次调用登记到新通道。同步、不抛错,不影响下面旧 GET 的任何行为。 */
11
+ capture?: (params: ReportUsageParams) => void;
10
12
  }
11
13
  /**
12
14
  * 兼容已有图片 GET 统计接口,改用 fetch 读取 HTTP 确认以便做有限重试。
@@ -1,7 +1,7 @@
1
1
  import { default as React } from 'react';
2
2
  import { AccountError } from './account';
3
3
  import { UseResult } from './consumption';
4
- import { ChatApi, ContentExtractionApi, ErrorReportingApi, PredictionApi, TextModerationApi, TextToSpeechApi, UploadApi, UsageApi, UsageReportingApi, VttApi } from '../api/types';
4
+ import { ChatApi, ContentExtractionApi, ErrorReportingApi, PredictionApi, TelemetryApi, TextModerationApi, TextToSpeechApi, UploadApi, UsageApi, UsageReportingApi, VttApi } from '../api/types';
5
5
  import { canUseError, CheckoutSessionOptions, TestMode, UserStatus } from './interface';
6
6
  /**
7
7
  * `useYiChongCanva()` 返回的客户端:账户状态、历史额度方法和后端同名 API 共用一个 Provider。
@@ -9,7 +9,7 @@ import { canUseError, CheckoutSessionOptions, TestMode, UserStatus } from './int
9
9
  * `userStatus` 等字段随 React 渲染更新;后端 API 则在每次调用时读取 Provider 的最新身份引用。
10
10
  * use() 返回不会 reject 的消费结果;同名消费 API 仍保留原始响应并以 ApiError 表达失败。
11
11
  */
12
- export interface YiChongCanvaContextType extends PredictionApi, TextModerationApi, ContentExtractionApi, ChatApi, VttApi, TextToSpeechApi, UsageApi, UploadApi, ErrorReportingApi, UsageReportingApi {
12
+ export interface YiChongCanvaContextType extends PredictionApi, TextModerationApi, ContentExtractionApi, ChatApi, VttApi, TextToSpeechApi, UsageApi, UploadApi, ErrorReportingApi, UsageReportingApi, TelemetryApi {
13
13
  /** 当前账户快照;登录前为 `{}`。Canva 用户 ID 是 userId,系统用户 ID 是 profile.id。 */
14
14
  userStatus: UserStatus;
15
15
  /** 深度合并本地账户快照,并同步 API 使用的引用;不请求服务器,也不触发 onUpdateUserStatus。 */
@@ -30,8 +30,11 @@ export interface YiChongCanvaContextType extends PredictionApi, TextModerationAp
30
30
  * 同一账户的连续调用串行执行、使用最新余额;切换账户后旧队列不继续发新请求。
31
31
  * notUpload 仅阻止积分扣费请求,订阅月用量仍会发送。结果明确区分全成功、跳过、失败、部分成功和未知。
32
32
  * Promise 始终 resolve;旧应用可继续忽略返回值。partial 的 charged=true 仅表示部分已确认。
33
+ * 2.6.0:options.operationId 把结果关联到本次生成,新通道开启时自动发送 consume_result;不改变扣费行为。
33
34
  */
34
- use: (cnt?: number, force?: boolean, notUpload?: boolean) => Promise<UseResult>;
35
+ use: (cnt?: number, force?: boolean, notUpload?: boolean, options?: {
36
+ operationId?: string;
37
+ }) => Promise<UseResult>;
35
38
  /** 旧的纯本地判断:订阅用户在 force=false 时直接通过,不考虑月限额;force=true 只检查积分。 */
36
39
  canUse: (cnt?: number, force?: boolean) => boolean;
37
40
  /** 纯本地额度判断,默认检查 1 次;考虑月额度和积分。force=true 只查积分,免费无限仍直接通过。 */
@@ -1,6 +1,7 @@
1
1
  import { default as React } from 'react';
2
2
  import { Mode, TestMode, UserStatus } from './interface';
3
3
  import { UsageReportingConfig } from '../api/types';
4
+ import { TelemetryConfig } from '../api/telemetry/types';
4
5
  /**
5
6
  * 应用入口的账户与 API 配置。不同服务有独立根地址,修改其中一个不会自动改写其他服务地址。
6
7
  * productName 应使用后端登记的应用渠道名称,而不是界面中可随意修改的标题。
@@ -34,6 +35,12 @@ export interface YiChongCanvaProviderProps {
34
35
  * 自动补充当前身份、会话及应用发布号,登录前可发送;不读取或上报业务输入、结果正文。
35
36
  */
36
37
  usageReporting?: UsageReportingConfig;
38
+ /**
39
+ * 2.6.0:新通道(canva.v1),默认关闭。开启后 reportUsage / reportError / track / use 的结果
40
+ * 额外发一份到采集 Worker;旧 GET 统计和飞书错误上报的行为完全不变。
41
+ * usageReporting.enabled=false 时新通道同样关闭。
42
+ */
43
+ telemetry?: TelemetryConfig;
37
44
  /** 默认 true,挂载后自动登录;false 时由 client.handleLogin/manualLogin 显式启动。 */
38
45
  autoLogin?: boolean;
39
46
  /** 初始模拟模式,默认 noTest;挂载 effect 会将开发环境设为 credits、其他环境设为 noTest。 */
@@ -67,4 +74,4 @@ export interface YiChongCanvaProviderProps {
67
74
  * // App 或其子组件内:const client = useYiChongCanva();
68
75
  * // 账号就绪后,直接调用 client.createSpecifyPrediction({ owner, name, input })。
69
76
  */
70
- export declare const YiChongCanvaProvider: ({ children, appId, productName, onUpdateUserStatus, baseUrl, apiBaseUrl, contentBaseUrl, chatBaseUrl, ttsBaseUrl, uploadBaseUrl, getLocale, usageReporting, autoLogin, testMode: _testMode, version, mode, retry, maxAvailablePoints, }: YiChongCanvaProviderProps) => React.JSX.Element;
77
+ export declare const YiChongCanvaProvider: ({ children, appId, productName, onUpdateUserStatus, baseUrl, apiBaseUrl, contentBaseUrl, chatBaseUrl, ttsBaseUrl, uploadBaseUrl, getLocale, usageReporting, telemetry: telemetryConfig, autoLogin, testMode: _testMode, version, mode, retry, maxAvailablePoints, }: YiChongCanvaProviderProps) => React.JSX.Element;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "yichong-canva2",
3
- "version": "2.5.1",
3
+ "version": "2.6.0",
4
4
  "type": "module",
5
5
  "main": "./dist/index.js",
6
6
  "module": "./dist/index.js",