yichong-canva2 2.3.0 → 2.5.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.
@@ -0,0 +1,76 @@
1
+ import { ApiError } from "./error.js";
2
+ import { addContextQuery, language } from "./request.js";
3
+ import { withRequest } from "./transport.js";
4
+ import { usageReportingData, usageReportingText } from "./usage_reporting_payload.js";
5
+ function createUsageReportingApi(getContext) {
6
+ return {
7
+ async reportUsage(params, options = {}) {
8
+ var _a, _b, _c, _d, _e;
9
+ try {
10
+ const context = getContext();
11
+ const config = context.usageReporting ?? {};
12
+ if (config.enabled === false || ((_a = options.signal) == null ? void 0 : _a.aborted)) return false;
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;
15
+ const appKey = config.appKey ?? `${context.productName}_canva`;
16
+ if (typeof appKey !== "string" || !/^[a-zA-Z0-9_.:-]{1,128}$/.test(appKey)) return false;
17
+ const timeoutMs = options.timeoutMs ?? 4e3;
18
+ if (!Number.isInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > 4e3) return false;
19
+ const url = new URL(config.endpoint ?? "https://log.aibabygenerator.io/api/report");
20
+ 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);
22
+ const occurredAt = (/* @__PURE__ */ new Date()).toISOString();
23
+ const base = usageReportingData({ ...context.metadata, occurred_at: occurredAt }, secrets);
24
+ const attributes = usageReportingData(params.data, secrets);
25
+ 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;
27
+ if (userId !== void 0 && (typeof userId !== "string" || userId.length > 128)) return false;
28
+ const title = usageReportingText(params.title, 128, secrets);
29
+ url.searchParams.set("app_key", appKey);
30
+ url.searchParams.set("sum_key", params.sum_key);
31
+ url.searchParams.set("title", title);
32
+ if (userId) url.searchParams.set("user_id", userId);
33
+ url.searchParams.set("timestamp", String(Date.now()));
34
+ url.searchParams.set("uuid", globalThis.crypto.randomUUID());
35
+ addContextQuery(url, context);
36
+ const headers = { "Accept-Language": language(context.getLocale) };
37
+ const updateData = () => url.searchParams.set("data", encodeURIComponent(JSON.stringify(data)));
38
+ updateData();
39
+ for (const key of Object.keys(data).reverse()) {
40
+ if (url.href.length <= 8192) break;
41
+ if (key === "occurred_at") continue;
42
+ delete data[key];
43
+ updateData();
44
+ }
45
+ if (url.href.length > 8192) return false;
46
+ const requestUrl = url.toString();
47
+ for (let attempt = 0; attempt < 2; attempt++) {
48
+ if ((_e = options.signal) == null ? void 0 : _e.aborted) return false;
49
+ try {
50
+ const response = await withRequest({ signal: options.signal, timeoutMs }, (signal) => fetch(requestUrl, {
51
+ method: "GET",
52
+ headers,
53
+ signal,
54
+ credentials: "omit",
55
+ redirect: "error",
56
+ referrerPolicy: "no-referrer",
57
+ cache: "no-store",
58
+ mode: "cors",
59
+ keepalive: true
60
+ }));
61
+ if (response.ok) return true;
62
+ if (response.status !== 429 && response.status < 500) return false;
63
+ } catch (error) {
64
+ if (!(error instanceof ApiError) || !["network_error", "timeout"].includes(String(error.code))) return false;
65
+ }
66
+ }
67
+ return false;
68
+ } catch {
69
+ return false;
70
+ }
71
+ }
72
+ };
73
+ }
74
+ export {
75
+ createUsageReportingApi
76
+ };
@@ -0,0 +1,44 @@
1
+ const sensitiveKey = /(?:prompt|input|output|content|message|text|file|image|audio|video|url|uri|token|passport|authorization|cookie|password|secret|credential|email|stack|rawerror|requestbody|responsebody)/i;
2
+ const redacted = "[redacted]";
3
+ function usageReportingText(value, maxLength, secrets) {
4
+ let clean = value;
5
+ for (const secret of secrets) {
6
+ if (typeof secret === "string" && secret.length >= 4) clean = clean.split(secret).join(redacted);
7
+ }
8
+ clean = clean.replace(/(?:https?:\/\/|blob:|data:|www\.)[^\s<>"']+/gi, redacted).replace(/\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}\b/gi, redacted).replace(/\bBearer\s+\S+/gi, redacted).replace(/\beyJ[A-Za-z0-9_-]*\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/g, redacted).replace(/[\u0000-\u001f\u007f]/g, " ");
9
+ return Array.from(clean).slice(0, maxLength).join("");
10
+ }
11
+ function usageReportingData(value, secrets) {
12
+ let fields = 0;
13
+ const seen = /* @__PURE__ */ new Set();
14
+ function clean(input, depth) {
15
+ if (input === null || typeof input === "boolean") return input;
16
+ if (typeof input === "string") return usageReportingText(input, 256, secrets);
17
+ if (typeof input === "number") return Number.isFinite(input) ? input : void 0;
18
+ if (!input || typeof input !== "object" || seen.has(input) || depth > 3) return void 0;
19
+ if (!Array.isArray(input) && Object.getPrototypeOf(input) !== Object.prototype && Object.getPrototypeOf(input) !== null) return void 0;
20
+ seen.add(input);
21
+ try {
22
+ if (Array.isArray(input)) {
23
+ return Object.values(Object.getOwnPropertyDescriptors(input)).slice(0, 10).filter((descriptor) => descriptor.enumerable && "value" in descriptor).map((descriptor) => clean(descriptor.value, depth + 1)).filter((item) => item !== void 0);
24
+ }
25
+ const output = /* @__PURE__ */ Object.create(null);
26
+ for (const [key, descriptor] of Object.entries(Object.getOwnPropertyDescriptors(input))) {
27
+ if (fields >= 30) break;
28
+ if (!descriptor.enumerable || !("value" in descriptor) || !/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/.test(key)) continue;
29
+ fields++;
30
+ const child = sensitiveKey.test(key.replace(/[_-]/g, "")) ? redacted : clean(descriptor.value, depth + 1);
31
+ if (child !== void 0) output[key] = child;
32
+ }
33
+ return output;
34
+ } finally {
35
+ seen.delete(input);
36
+ }
37
+ }
38
+ const result = clean(value, 0);
39
+ return result && typeof result === "object" && !Array.isArray(result) ? result : {};
40
+ }
41
+ export {
42
+ usageReportingData,
43
+ usageReportingText
44
+ };
package/dist/index.js CHANGED
@@ -1,10 +1,13 @@
1
1
  import { YiChongCanvaProvider } from "./login/privider.js";
2
2
  import { YiChongCanvaContext } from "./login/context.js";
3
3
  import { useYiChongCanva } from "./login/use_canva.js";
4
- import { ApiError } from "./api/error.js";
4
+ import { ApiError, isAbortError } from "./api/error.js";
5
+ import { getPredictionOutputUrl } from "./api/predictions.js";
5
6
  export {
6
7
  ApiError,
7
8
  YiChongCanvaContext,
8
9
  YiChongCanvaProvider,
10
+ getPredictionOutputUrl,
11
+ isAbortError,
9
12
  useYiChongCanva
10
13
  };
@@ -0,0 +1,38 @@
1
+ const versionCacheKey = (appId) => `yichong_version_${appId}`;
2
+ function testCacheKey(kind, appId, productName, userId, uid) {
3
+ return `yichong_${kind}_${encodeURIComponent(JSON.stringify([appId, productName, userId ?? "", uid ?? ""]))}`;
4
+ }
5
+ const passportCacheKey = (userId) => `${userId}_passport`;
6
+ const memory = /* @__PURE__ */ new Map();
7
+ function readCache(key) {
8
+ try {
9
+ const value = localStorage.getItem(key);
10
+ if (value === null) memory.delete(key);
11
+ else memory.set(key, value);
12
+ return value;
13
+ } catch {
14
+ return memory.get(key) ?? null;
15
+ }
16
+ }
17
+ function writeCache(key, value) {
18
+ memory.set(key, value);
19
+ try {
20
+ localStorage.setItem(key, value);
21
+ } catch {
22
+ }
23
+ }
24
+ function removeCache(key) {
25
+ memory.delete(key);
26
+ try {
27
+ localStorage.removeItem(key);
28
+ } catch {
29
+ }
30
+ }
31
+ export {
32
+ passportCacheKey,
33
+ readCache,
34
+ removeCache,
35
+ testCacheKey,
36
+ versionCacheKey,
37
+ writeCache
38
+ };
@@ -0,0 +1,94 @@
1
+ import { ApiError } from "../api/error.js";
2
+ const skippedUsage = (reason) => ({
3
+ status: "skipped",
4
+ charged: false,
5
+ reason,
6
+ confirmed: { monthly: 0, freeCnt: 0 }
7
+ });
8
+ function usageFailure(error) {
9
+ const code = error instanceof ApiError ? error.code : "network_error";
10
+ const knownCodes = ["network_error", "timeout", "aborted", "invalid_response", "invalid_request", "account_not_ready", "http_error"];
11
+ return {
12
+ // 后端可能把自由文本放进 code;仅保留数字业务码和 SDK 定义的字符串码。
13
+ code: typeof code === "number" || knownCodes.includes(code) ? code : "backend_rejected",
14
+ message: "Usage recording could not be confirmed.",
15
+ ...error instanceof ApiError && error.status !== void 0 ? { status: error.status } : {}
16
+ };
17
+ }
18
+ function invalidUsageResult() {
19
+ return {
20
+ status: "failed",
21
+ charged: false,
22
+ reason: "invalid_count",
23
+ confirmed: { monthly: 0, freeCnt: 0 },
24
+ error: { code: "invalid_request", message: "cnt must be a positive number within the safe numeric range." }
25
+ };
26
+ }
27
+ function isValidUsageCount(cnt) {
28
+ return typeof cnt === "number" && Number.isFinite(cnt) && cnt > 0 && cnt <= Number.MAX_SAFE_INTEGER / 100;
29
+ }
30
+ async function recordUsage(options) {
31
+ const { monthly, freeCnt, notUpload, api, isCurrent, report } = options;
32
+ const confirmed = { monthly: 0, freeCnt: 0 };
33
+ const channel = monthly > 0 ? freeCnt > 0 ? "monthly_and_free_cnt" : "monthly" : "free_cnt";
34
+ let stage = "use_monthly";
35
+ const skip = (reason) => confirmed.monthly > 0 ? { status: "partial", charged: true, channel: "monthly_and_free_cnt", confirmed, remaining: "skipped", reason } : skippedUsage(reason);
36
+ try {
37
+ if (!isCurrent()) return skip("account_changed");
38
+ if (monthly > 0) {
39
+ await api.addMonthlyUsage({ cnt: monthly });
40
+ confirmed.monthly = monthly;
41
+ }
42
+ if (freeCnt > 0) {
43
+ if (!isCurrent()) return skip("account_changed");
44
+ if (notUpload) return skip("not_upload");
45
+ stage = "reduce_free_cnt";
46
+ await api.reduceFreeCnt({ cnt: freeCnt });
47
+ confirmed.freeCnt = freeCnt;
48
+ }
49
+ return { status: "charged", charged: true, channel, confirmed };
50
+ } catch (error) {
51
+ const failure = usageFailure(error);
52
+ const unknown = ["timeout", "network_error", "aborted", "invalid_response"].includes(String(failure.code)) || failure.status !== void 0 && failure.status >= 500;
53
+ try {
54
+ void Promise.resolve(report({
55
+ error: failure.message,
56
+ source: "api",
57
+ stage,
58
+ context: {
59
+ code: failure.code,
60
+ http_status: failure.status ?? 0,
61
+ monthly_confirmed: confirmed.monthly,
62
+ free_cnt_confirmed: confirmed.freeCnt,
63
+ outcome: unknown ? "unknown" : "failed"
64
+ }
65
+ })).catch(() => {
66
+ });
67
+ } catch {
68
+ }
69
+ if (confirmed.monthly > 0 || confirmed.freeCnt > 0) {
70
+ return {
71
+ status: "partial",
72
+ charged: true,
73
+ channel: "monthly_and_free_cnt",
74
+ confirmed,
75
+ remaining: unknown ? "unknown" : "failed",
76
+ error: failure
77
+ };
78
+ }
79
+ return unknown ? { status: "unknown", charged: null, channel, confirmed, error: failure } : {
80
+ status: "failed",
81
+ charged: false,
82
+ confirmed,
83
+ reason: failure.code === "account_not_ready" ? "account_not_ready" : "request_failed",
84
+ error: failure
85
+ };
86
+ }
87
+ }
88
+ export {
89
+ invalidUsageResult,
90
+ isValidUsageCount,
91
+ recordUsage,
92
+ skippedUsage,
93
+ usageFailure
94
+ };
@@ -11,8 +11,13 @@ const YiChongCanvaContext = React.createContext(
11
11
  getLimitUsage: () => null,
12
12
  getMonthlyUsageLimit: () => null,
13
13
  isSubscribed: false,
14
- use: () => {
15
- },
14
+ use: async () => ({
15
+ status: "failed",
16
+ charged: false,
17
+ reason: "account_not_ready",
18
+ confirmed: { monthly: 0, freeCnt: 0 },
19
+ error: { code: "provider_missing", message: "Wrap your components in YiChongCanvaProvider first." }
20
+ }),
16
21
  canUse: () => false,
17
22
  canUseLimit: () => ({ canUse: false }),
18
23
  isFreeUnlimited: () => false,
@@ -37,6 +42,12 @@ const YiChongCanvaContext = React.createContext(
37
42
  getPrediction: async () => {
38
43
  throw new ApiError("Wrap your components in YiChongCanvaProvider first.", "provider_missing");
39
44
  },
45
+ cancelPrediction: async () => {
46
+ throw new ApiError("Wrap your components in YiChongCanvaProvider first.", "provider_missing");
47
+ },
48
+ waitForPrediction: async () => {
49
+ throw new ApiError("Wrap your components in YiChongCanvaProvider first.", "provider_missing");
50
+ },
40
51
  textCheck: async () => {
41
52
  throw new ApiError("Wrap your components in YiChongCanvaProvider first.", "provider_missing");
42
53
  },
@@ -52,9 +63,16 @@ const YiChongCanvaContext = React.createContext(
52
63
  getVttStatus: async () => {
53
64
  throw new ApiError("Wrap your components in YiChongCanvaProvider first.", "provider_missing");
54
65
  },
66
+ createTextToSpeech: async () => {
67
+ throw new ApiError("Wrap your components in YiChongCanvaProvider first.", "provider_missing");
68
+ },
69
+ getTextToSpeechResult: async () => {
70
+ throw new ApiError("Wrap your components in YiChongCanvaProvider first.", "provider_missing");
71
+ },
55
72
  reportError: async () => {
56
73
  throw new ApiError("Wrap your components in YiChongCanvaProvider first.", "provider_missing");
57
74
  },
75
+ reportUsage: async () => false,
58
76
  reduceFreeCnt: async () => {
59
77
  throw new ApiError("Wrap your components in YiChongCanvaProvider first.", "provider_missing");
60
78
  },
@@ -1,6 +1,7 @@
1
1
  import { accountRequest } from "./request.js";
2
2
  import { isObject } from "../../../api/request.js";
3
3
  import { throwIfAborted } from "../../../api/transport.js";
4
+ import { readCache, passportCacheKey, writeCache } from "../../cache.js";
4
5
  const headers = {
5
6
  "Content-Type": "application/json"
6
7
  };
@@ -32,7 +33,7 @@ function handleUserLoginByCanvaId(userId, productName, context, options = {}) {
32
33
  }
33
34
  function getPassport(userId, productName, context, options = {}) {
34
35
  if (options.signal) throwIfAborted(options.signal);
35
- const passport = localStorage.getItem(userId + "_passport");
36
+ const passport = readCache(passportCacheKey(userId));
36
37
  if (passport) {
37
38
  return Promise.resolve({
38
39
  data: {
@@ -54,7 +55,7 @@ function getPassport(userId, productName, context, options = {}) {
54
55
  redirect: "follow"
55
56
  }, context, "canva_passport", options, (body) => isObject(body.data) && typeof body.data.passport === "string" && !!body.data.passport).then((res) => {
56
57
  if (options.signal) throwIfAborted(options.signal);
57
- localStorage.setItem(userId + "_passport", res.data.passport);
58
+ writeCache(passportCacheKey(userId), res.data.passport);
58
59
  return res;
59
60
  });
60
61
  }
@@ -27,18 +27,6 @@ function accountRequest(option, context, stage, options = {}, validate) {
27
27
  return body;
28
28
  }, api);
29
29
  }
30
- function requestUrl(option, context) {
31
- const { url, ...init } = option;
32
- const target = new URL(url);
33
- if (context) {
34
- addContextQuery(target, context);
35
- const headers = new Headers(init.headers);
36
- headers.set("Accept-Language", language(context.getLocale));
37
- init.headers = headers;
38
- }
39
- return fetch(target.toString(), init).then((response) => response.json());
40
- }
41
30
  export {
42
- accountRequest,
43
- requestUrl as default
31
+ accountRequest
44
32
  };
@@ -4,6 +4,7 @@ import { isObject } from "../../api/request.js";
4
4
  import { ApiError } from "../../api/error.js";
5
5
  import { withRequest, throwIfAborted } from "../../api/transport.js";
6
6
  import { AccountRequestError, retryableAccountError, accountDelay, accountStep } from "../account.js";
7
+ import { removeCache, passportCacheKey } from "../cache.js";
7
8
  function accountContext(productName, userId, getContext) {
8
9
  const context = getContext == null ? void 0 : getContext();
9
10
  const current = context == null ? void 0 : context.userStatus;
@@ -139,7 +140,7 @@ async function getUserProfile({
139
140
  throwIfAborted(requestSignal);
140
141
  if (!userStatus.profile && !renewedPassport) {
141
142
  renewedPassport = true;
142
- localStorage.removeItem(userId + "_passport");
143
+ removeCache(passportCacheKey(userId));
143
144
  passport = (await apis.getPassport(userId, productName, requestContext(), options)).data.passport;
144
145
  userStatus = (await apis.getUserStatusByPassport(passport, productName, requestContext(), options)).data;
145
146
  throwIfAborted(requestSignal);