yichong-canva2 2.5.1 → 2.7.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.7.0(2026-10-27)**:配合后端 msg 分级,新增 `getDisplayMessage`、`getBackendErrorCode`、`isPolicyBlocked`,`ApiError` 增加 `errorCode`、`traceId`、`displayable`;新通道按后端 `error_code` 推断错误码和是否预期内。已有字段含义不变。见下文「错误文案(2.7.0 起)」。另外新增 `client.pricingUnit`:计量单位按渠道和界面语言从定价语言包读取,见「计量单位(2.7.0 起)」。
6
+
7
+ **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 起)」。
8
+
5
9
  **2.5.1**:只补类型、不改行为。`userStatus.profile` 增加后端 status 已返回的 `review?: boolean`(审核开关:true 审核期、false 正常运行、缺失为旧账户)、`canva_id?`、`created_at?`、`nextUsageResetTime?`。支付链接是否可点由应用按 `review === false || canAcceptPayments` 决定,SDK 不据此改变任何行为。
6
10
 
7
11
  **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 +125,7 @@ function GenerateButton() {
121
125
  | `client.getTextToSpeechResult({ jobId })`(2.4.0 起) | `POST {ttsBaseUrl}/api/text-to-speech/result` | `{ code: 0, msg, data: { jobId, status, status_str, result, remark } }` |
122
126
  | `client.reportUsage({ sum_key, title, data? })`(2.4.0 起) | `GET https://log.aibabygenerator.io/api/report` | `Promise<boolean>`;失败不抛错,不阻断业务 |
123
127
  | `client.reportError({ error, source?, stage?, api?, context? })` | `POST https://report.imgkits.com` | Worker 原始 `{ success: true, data: { code: 0, ... } }` 或过滤响应 |
128
+ | `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
129
  | `client.reduceFreeCnt({ cnt })` | `POST {baseUrl}/api/user/reduce-free-cnt` | `{ ok: 0, msg: "success" }` |
125
130
  | `client.addMonthlyUsage({ cnt })` | `POST {baseUrl}/api/user/add-monthly-usage` | `{ ok: 0, msg: "success" }` |
126
131
  | `client.addFreeUsageCnt({ cnt })` | `POST {baseUrl}/api/user/add-free-usage-cnt` | `{ ok: 0, msg: "success" }` |
@@ -684,6 +689,51 @@ const prediction = await client.getPrediction(
684
689
 
685
690
  取消只终止当前 HTTP 等待,不会取消已经创建的后端任务或撤销已提交的消费。创建、查询、文本审核和底层签名的默认请求超时为 60 秒,包含读取响应正文的时间;内容提取和大模型 `chat` 为 360 秒,消费为 30 秒,单次 PUT 上传为 120 秒,分片上传整体为 30 分钟。
686
691
 
692
+ ## 错误文案(2.7.0 起)
693
+
694
+ 后端对 `createSpecifyPrediction`、`getPrediction` 做了 msg 分级:失败时的 `msg`、任务的 `error_msg` / `error` 都是按 `Accept-Language` 翻译好的用户文案,原文挪到 `debug_msg` / `raw_*`(约定见仓库 `docs/前后端约定-错误文案msg分级.md`)。界面取文案只用 `getDisplayMessage`,取不到再显示应用自己的翻译文案:
695
+
696
+ ```ts
697
+ import { getDisplayMessage, isPolicyBlocked } from "yichong-canva2";
698
+
699
+ function describeFailure(error: unknown): string {
700
+ return getDisplayMessage(error) // 后端分级后的用户文案
701
+ || (isPolicyBlocked(error) ? policyText // 内容违规:换图 / 换样式
702
+ : fallbackText); // 应用自己的翻译兜底
703
+ }
704
+ ```
705
+
706
+ | 字段 / 函数 | 含义 |
707
+ | --- | --- |
708
+ | `ApiError.displayable` | message 能原样展示时为 true。创建失败看响应是否带 `debug_msg`,任务失败看任务是否带 `error_code`;其它接口、SDK 本地错误恒为 false |
709
+ | `ApiError.errorCode` | 后端 `error_code`(snake_case),逻辑判断只看它 |
710
+ | `ApiError.traceId` | 后端 `trace_id`(创建接口),新通道放进 `request_id` |
711
+ | `getDisplayMessage(error)` | 可展示的后端文案,没有返回 `""`;会顺着 `StageError` / `Error.cause` 找,最多 5 层 |
712
+ | `getBackendErrorCode(error)` | 后端 `error_code`,没有返回 `undefined` |
713
+ | `isPolicyBlocked(error)` | 后端判定内容违规(`content_policy_violation`),或 `StageError` 的 code 为 `POLICY_BLOCKED` |
714
+
715
+ - 不再需要维护「SDK 本地错误码清单」,也不要再用正则匹配 `E005`。
716
+ - 新通道:后端 `content_policy_violation` 记为 `POLICY_BLOCKED`(`generate_blocked`,不告警);`image_unavailable`、`invalid_input`、`too_many_concurrent_tasks`、`image_preprocessing_failed`、`no_output` 记为预期内。
717
+ - `code`、`userMessage` 含义不变:创建失败的 `code` 仍是后端数字 `1`,任务失败仍是 `prediction_failed`。
718
+ - 后端没打开分级时 `displayable` 一律为 false,应用显示自己的兜底文案。
719
+
720
+ ## 计量单位(2.7.0 起)
721
+
722
+ `client.pricingUnit` 是定价语言包里的计量单位,和定价页用同一份文件:改了定价单位,用户下次打开应用就生效,不用前端发版。
723
+
724
+ ```ts
725
+ const { pricingUnit } = useYiChongCanva();
726
+ // { unitNoun: "Quiz", unitNounPlural: "Quizze", locale: "de" },读取中或拿不到时为 null
727
+ const unitNoun = pricingUnit?.unitNoun ?? appConfig.unitConfig.unitNoun;
728
+ ```
729
+
730
+ - 地址:`https://project.deletetweets.ai/yichong_pricing_language/<productName>/<语言>.json` 的 `config.unit` / `config.plural_unit`。
731
+ - 语言:取界面语言的主语言(`zh-TW` → `zh`,`pt-BR` → `pt`),没有语言包再退到 `en`;换语言时重新读取,期间保留上一份单位,换渠道时旧单位作废。
732
+ - 每次打开都用 `cache: "no-cache"` 带 ETag 校验,没变时只回 304;单次 10 秒超时,不阻塞登录。
733
+ - 404、断网、超时、格式不对(非字符串、超过 40 字符、含 `<>{}`)都只得到 `null`,不抛错、不上报:部分渠道本来就没有定价语言包,应用退回 `config.ts` 的 `unitConfig`。
734
+ - 复数沿用「1 用单数,其余用复数」;语言包没有 `plural_unit` 时复数等于单数。
735
+ - 也导出了 `loadPricingUnit(productName, locale, signal?)`,供不用 Provider 的场景使用。
736
+
687
737
  ## 账户故障处理(2.2.0)
688
738
 
689
739
  继续使用一个 `YiChongCanvaProvider`,无需额外的上报 Provider 或 Footer 上报包装。账户模块会自动报告最终失败,业务 API 的错误仍在业务 catch 中按需显式调用 `client.reportError`。
@@ -808,3 +858,60 @@ void client.reportUsage({
808
858
  返回值为 `Promise<boolean>`:收到 HTTP 成功确认时为 true;关闭、非法参数、身份 getter/序列化异常、取消、网络等失败均为 false,不向业务抛错、不显示错误、不递归告警。通常 `void client.reportUsage(...)` 即可。默认每次请求 4 秒,网络/超时/429/5xx 最多重试一次,其他 4xx 不重试;第二参数 `{ signal, timeoutMs }` 可取消或缩短等待(1–4000 毫秒,每次)。
809
859
 
810
860
  只传枚举、计数、耗时、错误码等少量属性,不传提示词、完整 input/output、文件、资源地址、token、stack 或原始异常。SDK 会脱敏敏感字段和值,跳过 getter/toJSON/类实例,最多 3 层、30 个字段、数组 10 项、字符串 256 字符;最终 URL 上限 8192 字符,超长时先移除尾部业务属性。脱敏无法识别任意改名的用户文本,应用仍需只提供必要统计数据。统计失败不影响 Footer 原样式、加载状态或文案。
861
+
862
+ ## 新通道(2.6.0 起)
863
+
864
+ 新通道按 schema `canva.v1` 把行为和错误放进同一个事件流,批量发到 `https://telemetry.imgkits.com/v1/events`。完整设计见仓库 `docs/canva-telemetry/`(01 事件格式、02 SDK 上报层)。
865
+
866
+ **默认关闭。** 不传 `telemetry` 或 `enabled: false` 时不发出任何新通道请求。旧通道(GET 统计、飞书错误上报)在开启前后完全相同。`usageReporting={{ enabled: false }}` 同时关闭两条通道。
867
+
868
+ ```tsx
869
+ <YiChongCanvaProvider
870
+ appId="YOUR_CANVA_APP_ID"
871
+ productName="your_app_channel"
872
+ baseUrl="https://usa.imgkits.com/your_app_channel"
873
+ version={1}
874
+ telemetry={{ enabled: true }} // 默认 false;endpoint 默认 https://telemetry.imgkits.com/v1/events
875
+ >
876
+ <App />
877
+ </YiChongCanvaProvider>
878
+ ```
879
+
880
+ 开启后:
881
+
882
+ - `reportUsage` 和 `reportError` 的每次调用都会额外登记一条新通道事件(`reportError` 记为 `app_error`);`generate_retry` 不进新通道(由 `generate_start` 的 `retry_of` 表达);`data.mode: "demo"` 的事件记为 `env: "dev"`。
883
+ - Provider 的账户事件(`app_open`、`login_*`、`account_*`)自动进入新通道;`login_fail` / `account_fail` 带 `error`(`stage: "account"`)。
884
+ - `use(cnt, force, notUpload, { operationId })` 结束后自动发 `consume_result`(`status`、`cnt`;失败或未知时带 `error`)。不改变扣费行为。
885
+
886
+ 新增的可选字段和方法:
887
+
888
+ ```ts
889
+ import { StageError, createStageTimer, toErrorCode } from "yichong-canva2";
890
+
891
+ // 1. 记录每一步耗时;失败时抛 StageError,携带失败步骤和错误码
892
+ const timer = createStageTimer();
893
+ try {
894
+ const uploaded = await timer.run("upload", () => client.uploadFile({ file }, { signal }));
895
+ // ...
896
+ } catch (error) {
897
+ throw new StageError(error, { stage: "upload", code: toErrorCode(error, "upload") });
898
+ }
899
+
900
+ // 2. reportUsage 新增 flow / timings / error,只进新通道
901
+ void client.reportUsage({
902
+ sum_key: "generate_fail", title: "Generation failed",
903
+ data: { operation_id: operationId, duration_ms },
904
+ timings: timer.timings,
905
+ error: { stage: "upload", cause: error }, // code 省略时由 SDK 推断;cause 为 StageError 时直接取它的 stage/code
906
+ });
907
+
908
+ // 3. 新事件和自定义事件用 track,只进新通道,同步返回、永不抛错
909
+ client.track({ name: "quota_blocked", props: { cost: 2, state: "insufficient" } });
910
+ ```
911
+
912
+ - 应用使用这些新字段或方法时,依赖须为 `yichong-canva2@^2.6.0`。旧版本的 `reportUsage` 收到未知字段会返回 `false` 且不发送。
913
+ - `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`。
914
+ - 审核拦截请用错误码 `POLICY_BLOCKED`:`generate_fail` 带这个错误码时,新通道记为 `generate_blocked`。
915
+ - `props` 只保留扁平的字符串、数字、布尔或 null,最多 20 个;键名命中 `prompt`、`text`、`url`、`token`、`file_name` 等敏感词,或值里含 URL、邮箱、JWT 时,整键丢弃。
916
+ - `env`:页面运行在 localhost、测试模式(`updateTestMode`)或 `mode: "demo"` 时为 `dev`;审核期为 `review`;其余为 `production`。注意发布产物的 `NODE_ENV` 固定为 production,不能据此判断开发环境。
917
+ - 发送:满 20 条或 5 秒发一批,页面隐藏和 Provider 卸载时用 `keepalive` 发送剩余事件;只对网络、超时、429、5xx 重试两次;服务端返回 503 或 `pause_seconds` 后本会话停止发送;每会话最多 500 条;同一错误 60 秒内合并为 `repeat_count`。不读写本地存储。
package/dist/api/error.js CHANGED
@@ -3,7 +3,7 @@ class ApiError extends Error {
3
3
  * @param message 可展示的错误说明。
4
4
  * @param code 后端业务码或 SDK 标识,例如 invalid_request、timeout、network_error。
5
5
  * @param status 已取得的 HTTP 状态;请求发出前的错误等情况通常没有此值。
6
- * @param details 可选诊断数据和 Retry-After 秒数;仅提供信息,不触发重试。
6
+ * @param details 可选诊断数据、Retry-After 秒数和后端分级信息;仅提供信息,不触发重试。
7
7
  */
8
8
  constructor(message, code, status, details) {
9
9
  super(message);
@@ -13,12 +13,38 @@ class ApiError extends Error {
13
13
  this.userMessage = message;
14
14
  this.data = details == null ? void 0 : details.data;
15
15
  this.retryAfter = details == null ? void 0 : details.retryAfter;
16
+ this.errorCode = typeof (details == null ? void 0 : details.errorCode) === "string" && errorCodePattern.test(details.errorCode) ? details.errorCode : void 0;
17
+ this.traceId = typeof (details == null ? void 0 : details.traceId) === "string" && details.traceId.trim() ? details.traceId.trim().slice(0, 128) : void 0;
18
+ this.displayable = (details == null ? void 0 : details.displayable) === true && message.trim().length > 0;
16
19
  }
17
20
  }
21
+ const errorCodePattern = /^[a-z][a-z0-9_]{1,63}$/;
22
+ const MAX_CAUSE_DEPTH = 5;
23
+ function findInChain(error, pick) {
24
+ let current = error;
25
+ for (let depth = 0; depth <= MAX_CAUSE_DEPTH && current !== null && typeof current === "object"; depth++) {
26
+ const found = pick(current);
27
+ if (found !== void 0) return found;
28
+ current = current.cause;
29
+ }
30
+ return void 0;
31
+ }
32
+ function getDisplayMessage(error) {
33
+ return findInChain(error, (value) => value instanceof ApiError && value.displayable ? value.message.trim() : void 0) ?? "";
34
+ }
35
+ function getBackendErrorCode(error) {
36
+ return findInChain(error, (value) => value instanceof ApiError ? value.errorCode : void 0);
37
+ }
38
+ function isPolicyBlocked(error) {
39
+ return findInChain(error, (value) => value instanceof ApiError && value.errorCode === "content_policy_violation" || !(value instanceof ApiError) && value.code === "POLICY_BLOCKED" ? true : void 0) === true;
40
+ }
18
41
  function isAbortError(error) {
19
42
  return error instanceof ApiError ? error.code === "aborted" : error !== null && typeof error === "object" && "name" in error && error.name === "AbortError";
20
43
  }
21
44
  export {
22
45
  ApiError,
23
- isAbortError
46
+ getBackendErrorCode,
47
+ getDisplayMessage,
48
+ isAbortError,
49
+ isPolicyBlocked
24
50
  };
@@ -124,8 +124,13 @@ function createPredictionApi(getContext) {
124
124
  }
125
125
  if (task) {
126
126
  if (["failed", "canceled", "aborted"].includes(task.status)) {
127
- const message = [task.error_msg, task.error].find(isNonemptyString) || "Generation failed.";
128
- throw new ApiError(message, "prediction_failed", void 0, { data: { id: task.id, status: task.status } });
127
+ const message = [task.error_msg, task.error].find(isNonemptyString);
128
+ const errorCode = isNonemptyString(task.error_code) ? task.error_code : void 0;
129
+ throw new ApiError(message || "Generation failed.", "prediction_failed", void 0, {
130
+ data: { id: task.id, status: task.status, ...errorCode ? { error_code: errorCode } : {} },
131
+ errorCode,
132
+ displayable: errorCode !== void 0 && message !== void 0
133
+ });
129
134
  }
130
135
  if (task.status === "succeeded" || allowEarlyOutput && getPredictionOutputUrl(task.output)) return task;
131
136
  }
@@ -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.7.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
  };
@@ -77,15 +77,20 @@ async function readJson(response) {
77
77
  throw new ApiError("Backend returned an invalid JSON response.", response.ok ? "invalid_response" : "http_error", response.status);
78
78
  }
79
79
  }
80
- function backendError(response, payload, fallbackCode) {
81
- const message = isObject(payload) && isNonemptyString(payload.msg) ? payload.msg : isObject(payload) && isNonemptyString(payload.message) ? payload.message : "Backend request failed.";
80
+ function backendError(response, payload, fallbackCode, options = {}) {
81
+ const hasMsg = isObject(payload) && isNonemptyString(payload.msg);
82
+ const message = hasMsg ? payload.msg : isObject(payload) && isNonemptyString(payload.message) ? payload.message : "Backend request failed.";
82
83
  const code = isObject(payload) && (typeof payload.code === "string" || typeof payload.code === "number") ? payload.code : fallbackCode;
83
84
  const retryAfter = response.headers.get("Retry-After");
84
85
  return new ApiError(message, code, response.status, {
85
86
  data: isObject(payload) && isObject(payload.data) ? payload.data : void 0,
86
- retryAfter: retryAfter !== null && /^\d+$/.test(retryAfter) && Number.isSafeInteger(Number(retryAfter)) ? Number(retryAfter) : void 0
87
+ retryAfter: retryAfter !== null && /^\d+$/.test(retryAfter) && Number.isSafeInteger(Number(retryAfter)) ? Number(retryAfter) : void 0,
88
+ errorCode: isObject(payload) ? payload.error_code : void 0,
89
+ traceId: isObject(payload) ? payload.trace_id : void 0,
90
+ displayable: options.tiered === true && hasMsg && isObject(payload) && typeof payload.debug_msg === "string"
87
91
  });
88
92
  }
93
+ const tieredMethods = /* @__PURE__ */ new Set(["createSpecifyPrediction"]);
89
94
  async function postApi(context, method, params, options = {}) {
90
95
  return withRequest(options, async (signal) => {
91
96
  var _a;
@@ -114,14 +119,15 @@ async function postApi(context, method, params, options = {}) {
114
119
  redirect: "error"
115
120
  });
116
121
  const payload = await readJson(response);
117
- if (!response.ok) throw backendError(response, payload, "http_error");
122
+ const tiered = tieredMethods.has(method);
123
+ if (!response.ok) throw backendError(response, payload, "http_error", { tiered });
118
124
  if (method === "cancelPrediction" && isObject(payload) && payload.code === void 0) {
119
125
  return payload;
120
126
  }
121
127
  if (!isObject(payload) || typeof payload.code !== "number" && typeof payload.code !== "string") {
122
128
  throw new ApiError("Backend returned an invalid response envelope.", "invalid_response", response.status);
123
129
  }
124
- if (payload.code !== 0) throw backendError(response, payload, "http_error");
130
+ if (payload.code !== 0) throw backendError(response, payload, "http_error", { tiered });
125
131
  if (typeof payload.msg !== "string" || !Object.prototype.hasOwnProperty.call(payload, "data")) {
126
132
  throw new ApiError("Backend returned an invalid response envelope.", "invalid_response", response.status);
127
133
  }
@@ -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.7.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
+ };