yichong-canva2 2.0.0 → 2.2.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.
Files changed (39) hide show
  1. package/README.md +124 -24
  2. package/dist/api/error.js +6 -0
  3. package/dist/api/predictions.js +25 -6
  4. package/dist/api/reporting.js +4 -2
  5. package/dist/api/request.js +1 -0
  6. package/dist/api/uploads.js +121 -11
  7. package/dist/api/usage.js +3 -4
  8. package/dist/login/account.js +69 -0
  9. package/dist/login/context.js +1 -0
  10. package/dist/login/login/apis/index.js +17 -13
  11. package/dist/login/login/apis/request.js +33 -4
  12. package/dist/login/login/login.js +111 -103
  13. package/dist/login/privider.js +191 -125
  14. package/dist/types/api/chat.d.ts +6 -1
  15. package/dist/types/api/content.d.ts +5 -1
  16. package/dist/types/api/error.d.ts +14 -2
  17. package/dist/types/api/index.d.ts +6 -1
  18. package/dist/types/api/moderation.d.ts +5 -1
  19. package/dist/types/api/predictions.d.ts +5 -1
  20. package/dist/types/api/reporting.d.ts +7 -0
  21. package/dist/types/api/reporting_payload.d.ts +6 -1
  22. package/dist/types/api/request.d.ts +40 -2
  23. package/dist/types/api/transport.d.ts +7 -1
  24. package/dist/types/api/types.d.ts +231 -22
  25. package/dist/types/api/uploads.d.ts +7 -0
  26. package/dist/types/api/usage.d.ts +7 -1
  27. package/dist/types/index.d.ts +5 -0
  28. package/dist/types/login/account.d.ts +36 -0
  29. package/dist/types/login/context.d.ts +36 -35
  30. package/dist/types/login/index.d.ts +1 -0
  31. package/dist/types/login/interface.d.ts +35 -2
  32. package/dist/types/login/login/apis/index.d.ts +35 -17
  33. package/dist/types/login/login/apis/request.d.ts +10 -6
  34. package/dist/types/login/login/interface.d.ts +10 -1
  35. package/dist/types/login/login/login.d.ts +43 -21
  36. package/dist/types/login/privider.d.ts +34 -21
  37. package/dist/types/login/use_canva.d.ts +5 -2
  38. package/dist/types/login/version.d.ts +6 -0
  39. package/package.json +1 -1
@@ -0,0 +1,69 @@
1
+ import { ApiError } from "../api/error.js";
2
+ import { throwIfAborted, withRequest } from "../api/transport.js";
3
+ class AccountRequestError extends ApiError {
4
+ constructor(message, code, stage, api) {
5
+ super(message, code, api == null ? void 0 : api.status);
6
+ this.stage = stage;
7
+ this.api = api;
8
+ this.name = "AccountRequestError";
9
+ }
10
+ }
11
+ async function accountStep(stage, options, work, api) {
12
+ var _a;
13
+ (_a = options.onStep) == null ? void 0 : _a.call(options, stage, api);
14
+ try {
15
+ return await withRequest({ signal: options.signal, timeoutMs: 1e4 }, work);
16
+ } catch (error) {
17
+ if (error instanceof AccountRequestError) throw error;
18
+ const code = error instanceof ApiError ? error.code : "network_error";
19
+ throw new AccountRequestError(code === "timeout" ? "Account request timed out." : "Account request failed.", code, stage, api);
20
+ }
21
+ }
22
+ function retryableAccountError(error) {
23
+ return error instanceof ApiError && (error.code === "timeout" || error.code === "network_error" || error.status === 408 || error.status === 429 || error.status != null && error.status >= 500);
24
+ }
25
+ function accountDelay(ms, signal) {
26
+ throwIfAborted(signal);
27
+ return new Promise((resolve, reject) => {
28
+ const cleanup = () => {
29
+ clearTimeout(timer);
30
+ signal.removeEventListener("abort", cancel);
31
+ };
32
+ const cancel = () => {
33
+ cleanup();
34
+ reject(new ApiError("Request canceled.", "aborted"));
35
+ };
36
+ const timer = setTimeout(() => {
37
+ cleanup();
38
+ resolve();
39
+ }, ms);
40
+ signal.addEventListener("abort", cancel, { once: true });
41
+ });
42
+ }
43
+ function createAccountReporter(report) {
44
+ const sent = /* @__PURE__ */ new Map();
45
+ return (error, appKey) => {
46
+ var _a;
47
+ if (error.code === "aborted") return;
48
+ const now = Date.now();
49
+ for (const [key2, time] of sent) if (now - time >= 3e5) sent.delete(key2);
50
+ const key = [appKey, ((_a = error.api) == null ? void 0 : _a.url) ?? error.stage, error.status, error.code].join("|");
51
+ if (sent.has(key)) return;
52
+ sent.set(key, now);
53
+ void report({
54
+ error: new ApiError(error.message, error.code, error.status),
55
+ source: error.stage === "canva_token" ? "host_sdk" : "api",
56
+ stage: `account.${error.operation}.${error.stage}`,
57
+ api: error.api,
58
+ context: { attempts: error.attempts, elapsed_ms: error.elapsedMs }
59
+ }).catch(() => {
60
+ });
61
+ };
62
+ }
63
+ export {
64
+ AccountRequestError,
65
+ accountDelay,
66
+ accountStep,
67
+ createAccountReporter,
68
+ retryableAccountError
69
+ };
@@ -28,6 +28,7 @@ const YiChongCanvaContext = React.createContext(
28
28
  updateCredits: () => {
29
29
  },
30
30
  loginStatus: "idle",
31
+ accountError: null,
31
32
  manualLogin: () => {
32
33
  },
33
34
  createSpecifyPrediction: async () => {
@@ -1,24 +1,26 @@
1
- import requestUrl from "./request.js";
1
+ import { accountRequest } from "./request.js";
2
+ import { isObject } from "../../../api/request.js";
3
+ import { throwIfAborted } from "../../../api/transport.js";
2
4
  const headers = {
3
5
  "Content-Type": "application/json"
4
6
  };
5
7
  const baseUrl = "https://usa.imgkits.com/";
6
- function getUserIds(token, appId, context) {
8
+ function getUserIds(token, appId, context, options = {}) {
7
9
  const queryString = new URLSearchParams({
8
10
  canva_user_token: token,
9
11
  appid: appId
10
12
  }).toString();
11
13
  const url = `https://canva.livepolls.app/getUserIdByAppid?${queryString}`;
12
- return requestUrl({
14
+ return accountRequest({
13
15
  url,
14
16
  method: "GET",
15
17
  headers,
16
18
  redirect: "follow"
17
- }, context);
19
+ }, context, "canva_identity", options, (body) => isObject(body.verified) && typeof body.verified.userId === "string" && !!body.verified.userId);
18
20
  }
19
- function handleUserLoginByCanvaId(userId, productName, context) {
21
+ function handleUserLoginByCanvaId(userId, productName, context, options = {}) {
20
22
  const url = baseUrl + productName + "/api/user/canvaid-login";
21
- return requestUrl({
23
+ return accountRequest({
22
24
  url,
23
25
  method: "POST",
24
26
  headers,
@@ -26,9 +28,10 @@ function handleUserLoginByCanvaId(userId, productName, context) {
26
28
  canva_id: userId
27
29
  }),
28
30
  redirect: "follow"
29
- }, context);
31
+ }, context, "canvaid_login", options, (body) => body.ok === 0 || body.code === 0 || body.success === true);
30
32
  }
31
- function getPassport(userId, productName, context) {
33
+ function getPassport(userId, productName, context, options = {}) {
34
+ if (options.signal) throwIfAborted(options.signal);
32
35
  const passport = localStorage.getItem(userId + "_passport");
33
36
  if (passport) {
34
37
  return Promise.resolve({
@@ -41,7 +44,7 @@ function getPassport(userId, productName, context) {
41
44
  if (productName === "imgkits") {
42
45
  url = baseUrl + "/api/user/canva-passport";
43
46
  }
44
- return requestUrl({
47
+ return accountRequest({
45
48
  url,
46
49
  method: "POST",
47
50
  headers,
@@ -49,23 +52,24 @@ function getPassport(userId, productName, context) {
49
52
  canva_id: userId
50
53
  }),
51
54
  redirect: "follow"
52
- }, context).then((res) => {
55
+ }, context, "canva_passport", options, (body) => isObject(body.data) && typeof body.data.passport === "string" && !!body.data.passport).then((res) => {
56
+ if (options.signal) throwIfAborted(options.signal);
53
57
  localStorage.setItem(userId + "_passport", res.data.passport);
54
58
  return res;
55
59
  });
56
60
  }
57
- function getUserStatusByPassport(passport, productName, context) {
61
+ function getUserStatusByPassport(passport, productName, context, options = {}) {
58
62
  const header = {
59
63
  "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
60
64
  "X-Access-Ticket": passport
61
65
  };
62
66
  const url = baseUrl + productName + "/api/user/status";
63
- return requestUrl({
67
+ return accountRequest({
64
68
  url,
65
69
  method: "POST",
66
70
  headers: header,
67
71
  redirect: "follow"
68
- }, context);
72
+ }, context, "status", options, (body) => isObject(body.data));
69
73
  }
70
74
  const apis = {
71
75
  getUserIds,
@@ -1,5 +1,33 @@
1
- import { addContextQuery, language } from "../../../api/request.js";
2
- const requestUrl = (option, context) => {
1
+ import { addContextQuery, language, isObject } from "../../../api/request.js";
2
+ import { accountStep, AccountRequestError } from "../../account.js";
3
+ function accountRequest(option, context, stage, options = {}, validate) {
4
+ const { url, ...init } = option;
5
+ const target = new URL(url);
6
+ const api = { url: target.origin + target.pathname, method: init.method ?? "GET" };
7
+ addContextQuery(target, context);
8
+ const headers = new Headers(init.headers);
9
+ headers.set("Accept-Language", language(context.getLocale));
10
+ return accountStep(stage, options, async (signal) => {
11
+ const response = await fetch(target.toString(), { ...init, headers, signal });
12
+ const metadata = { ...api, status: response.status, request_id: response.headers.get("x-request-id") ?? void 0 };
13
+ if (!response.ok) throw new AccountRequestError("Account service returned an HTTP error.", "http_error", stage, metadata);
14
+ let body;
15
+ try {
16
+ body = await response.json();
17
+ } catch {
18
+ throw new AccountRequestError("Account service returned invalid JSON.", "invalid_response", stage, metadata);
19
+ }
20
+ if (!isObject(body)) throw new AccountRequestError("Account service returned invalid data.", "invalid_response", stage, metadata);
21
+ const failedCode = [body.ok, body.code].find((value) => value !== void 0 && value !== 0 && value !== "0");
22
+ if (body.success === false || failedCode !== void 0) {
23
+ const code = typeof failedCode === "string" || typeof failedCode === "number" ? failedCode : "account_rejected";
24
+ throw new AccountRequestError("Account service rejected the request.", code, stage, { ...metadata, response_code: code });
25
+ }
26
+ if (validate && !validate(body)) throw new AccountRequestError("Account service returned incomplete data.", "invalid_response", stage, metadata);
27
+ return body;
28
+ }, api);
29
+ }
30
+ function requestUrl(option, context) {
3
31
  const { url, ...init } = option;
4
32
  const target = new URL(url);
5
33
  if (context) {
@@ -8,8 +36,9 @@ const requestUrl = (option, context) => {
8
36
  headers.set("Accept-Language", language(context.getLocale));
9
37
  init.headers = headers;
10
38
  }
11
- return fetch(target.toString(), init).then((res) => res.json());
12
- };
39
+ return fetch(target.toString(), init).then((response) => response.json());
40
+ }
13
41
  export {
42
+ accountRequest,
14
43
  requestUrl as default
15
44
  };
@@ -1,5 +1,9 @@
1
1
  import { auth } from "@canva/user";
2
2
  import apis from "./apis/index.js";
3
+ import { isObject } from "../../api/request.js";
4
+ import { ApiError } from "../../api/error.js";
5
+ import { withRequest, throwIfAborted } from "../../api/transport.js";
6
+ import { AccountRequestError, retryableAccountError, accountDelay, accountStep } from "../account.js";
3
7
  function accountContext(productName, userId, getContext) {
4
8
  const context = getContext == null ? void 0 : getContext();
5
9
  const current = context == null ? void 0 : context.userStatus;
@@ -10,35 +14,32 @@ function accountContext(productName, userId, getContext) {
10
14
  };
11
15
  }
12
16
  auth.initOauth();
13
- async function handleLogin({
14
- appId,
15
- productName,
16
- onPassport,
17
- getRequestContext
18
- }) {
19
- try {
20
- let userId = window.userId;
21
- console.log("userId", userId);
22
- if (!userId) {
23
- const token = await auth.getCanvaUserToken();
24
- window.g_canva_token = token;
25
- const userIdResult = await apis.getUserIds(token, appId, accountContext(productName, userId, getRequestContext));
26
- userId = userIdResult.verified.userId;
27
- window.userId = userId;
28
- await apis.handleUserLoginByCanvaId(userId, productName, accountContext(productName, userId, getRequestContext));
29
- }
30
- const userStatus = await getUserProfile({
31
- userId,
32
- productName,
33
- onPassport,
34
- getRequestContext
35
- });
36
- window.g_token = userStatus.jwt || "";
37
- userStatus.userId = userId;
38
- return userStatus;
39
- } catch (e) {
40
- throw new Error("login failed");
17
+ async function handleLogin({ appId, productName, onPassport, getRequestContext, signal, onStep }) {
18
+ const options = { signal, onStep };
19
+ let userId = window.userId;
20
+ if (!userId) {
21
+ const token = await accountStep("canva_token", options, () => auth.getCanvaUserToken());
22
+ if (signal) throwIfAborted(signal);
23
+ window.g_canva_token = token;
24
+ const identity = await apis.getUserIds(token, appId, accountContext(productName, userId, getRequestContext), options);
25
+ userId = identity.verified.userId;
26
+ await apis.handleUserLoginByCanvaId(userId, productName, accountContext(productName, userId, getRequestContext), options);
27
+ if (signal) throwIfAborted(signal);
28
+ window.userId = userId;
41
29
  }
30
+ const userStatus = await getUserProfile({
31
+ userId,
32
+ productName,
33
+ onPassport,
34
+ getRequestContext,
35
+ ...options,
36
+ maxCount: 1
37
+ });
38
+ if (signal) throwIfAborted(signal);
39
+ if (!userStatus) throw new AccountRequestError("Account request canceled.", "aborted", "status");
40
+ window.g_token = userStatus.jwt || "";
41
+ userStatus.userId = userId;
42
+ return userStatus;
42
43
  }
43
44
  function takeSubscribeBaseline(userStatus) {
44
45
  const sub = userStatus == null ? void 0 : userStatus.subscription;
@@ -81,7 +82,7 @@ function isSubscribeChanged(current, baseline) {
81
82
  return false;
82
83
  }
83
84
  async function getUserProfile({
84
- maxCount = 50,
85
+ maxCount = 2,
85
86
  interval,
86
87
  maxDurationMs,
87
88
  productName,
@@ -93,87 +94,94 @@ async function getUserProfile({
93
94
  isChanged,
94
95
  onStop,
95
96
  onPassport,
96
- getRequestContext
97
+ getRequestContext,
98
+ signal,
99
+ onStep
97
100
  }) {
98
- var _a, _b;
99
- let count = 0;
100
- const startedAt = Date.now();
101
- let latestProfile;
102
- const requestContext = () => {
103
- const context = accountContext(productName, userId, getRequestContext);
104
- return { ...context, userStatus: { ...context.userStatus, profile: latestProfile ?? context.userStatus.profile } };
105
- };
106
- let passportResult = await apis.getPassport(userId, productName, requestContext());
107
- let passport = (_a = passportResult.data) == null ? void 0 : _a.passport;
108
- let isStop = false;
109
- let cancelSleep = null;
110
- let snapshot = baseline ?? null;
101
+ const controller = new AbortController();
102
+ let stopped = false;
103
+ const cancel = () => controller.abort();
104
+ if (signal == null ? void 0 : signal.aborted) controller.abort();
105
+ signal == null ? void 0 : signal.addEventListener("abort", cancel, { once: true });
111
106
  onStop == null ? void 0 : onStop(() => {
112
- isStop = true;
113
- count = maxCount;
114
- cancelSleep == null ? void 0 : cancelSleep();
107
+ stopped = true;
108
+ controller.abort();
115
109
  });
116
- const expired = () => count >= maxCount || maxDurationMs != null && Date.now() - startedAt >= maxDurationMs;
117
- while (!expired()) {
118
- console.log("poll", count);
119
- let userStatus;
120
- try {
121
- userStatus = await (await apis.getUserStatusByPassport(passport, productName, requestContext())).data;
122
- } catch (e) {
123
- userStatus = void 0;
124
- }
125
- if (userStatus == null ? void 0 : userStatus.profile) {
126
- latestProfile = userStatus.profile;
127
- if (typeof passport === "string" && passport) onPassport == null ? void 0 : onPassport(passport, userId, userStatus.profile.id);
128
- if (!isSubscribe) {
129
- successCallback == null ? void 0 : successCallback(userStatus);
130
- return userStatus;
131
- }
132
- if (!snapshot) {
133
- snapshot = takeSubscribeBaseline(userStatus);
134
- } else {
135
- const changed = isChanged ? isChanged(userStatus, snapshot) : isSubscribeChanged(userStatus, snapshot);
136
- if (changed) {
137
- console.log("subscribe success");
138
- successCallback == null ? void 0 : successCallback(userStatus);
139
- return userStatus;
110
+ let lastError;
111
+ let lastStage = "canva_passport";
112
+ let lastApi;
113
+ try {
114
+ return await withRequest({ signal: controller.signal, timeoutMs: maxDurationMs ?? (isSubscribe ? 3e5 : 3e4) }, async (requestSignal) => {
115
+ const options = { signal: requestSignal, onStep: (stage, api) => {
116
+ lastStage = stage;
117
+ lastApi = api;
118
+ onStep == null ? void 0 : onStep(stage, api);
119
+ } };
120
+ let latestProfile;
121
+ const requestContext = () => {
122
+ const context = accountContext(productName, userId, getRequestContext);
123
+ return { ...context, userStatus: { ...context.userStatus, profile: latestProfile ?? context.userStatus.profile } };
124
+ };
125
+ let passport = (await apis.getPassport(userId, productName, requestContext(), options)).data.passport;
126
+ let snapshot = baseline ?? null;
127
+ let consecutiveFailures = 0;
128
+ let renewedPassport = false;
129
+ for (let count = 0; count < maxCount; count++) {
130
+ throwIfAborted(requestSignal);
131
+ try {
132
+ let userStatus;
133
+ try {
134
+ userStatus = (await apis.getUserStatusByPassport(passport, productName, requestContext(), options)).data;
135
+ } catch (error) {
136
+ if (!(error instanceof ApiError && error.status === 401) || renewedPassport) throw error;
137
+ userStatus = {};
138
+ }
139
+ throwIfAborted(requestSignal);
140
+ if (!userStatus.profile && !renewedPassport) {
141
+ renewedPassport = true;
142
+ localStorage.removeItem(userId + "_passport");
143
+ passport = (await apis.getPassport(userId, productName, requestContext(), options)).data.passport;
144
+ userStatus = (await apis.getUserStatusByPassport(passport, productName, requestContext(), options)).data;
145
+ throwIfAborted(requestSignal);
146
+ }
147
+ if (!isObject(userStatus.profile) || typeof userStatus.profile.id !== "string" || !userStatus.profile.id || !isObject(userStatus.profile.usage_limits)) {
148
+ throw new AccountRequestError("Account status is missing a profile.", "invalid_response", "status", lastApi);
149
+ }
150
+ latestProfile = userStatus.profile;
151
+ onPassport == null ? void 0 : onPassport(passport, userId, userStatus.profile.id);
152
+ consecutiveFailures = 0;
153
+ lastError = void 0;
154
+ if (!isSubscribe) {
155
+ successCallback == null ? void 0 : successCallback(userStatus);
156
+ return userStatus;
157
+ }
158
+ if (!snapshot) snapshot = takeSubscribeBaseline(userStatus);
159
+ else if (isChanged ? isChanged(userStatus, snapshot) : isSubscribeChanged(userStatus, snapshot)) {
160
+ successCallback == null ? void 0 : successCallback(userStatus);
161
+ return userStatus;
162
+ }
163
+ } catch (error) {
164
+ throwIfAborted(requestSignal);
165
+ lastError = error;
166
+ consecutiveFailures++;
167
+ if (!retryableAccountError(error) || count + 1 >= maxCount || isSubscribe && consecutiveFailures >= 3) throw error;
140
168
  }
169
+ if (count + 1 < maxCount) await accountDelay(typeof interval === "function" ? interval() : interval ?? 3e3, requestSignal);
141
170
  }
142
- } else if (userStatus) {
143
- localStorage.removeItem(userId + "_passport");
144
- try {
145
- passportResult = await apis.getPassport(userId, productName, requestContext());
146
- passport = (_b = passportResult.data) == null ? void 0 : _b.passport;
147
- } catch (e) {
148
- }
149
- }
150
- count++;
151
- if (isStop || expired()) {
152
- break;
153
- }
154
- let ms = typeof interval === "function" ? interval() : interval ?? 3e3;
155
- if (maxDurationMs != null) {
156
- ms = Math.min(ms, Math.max(maxDurationMs - (Date.now() - startedAt), 0));
157
- }
158
- await sleep(ms, (cancel) => {
159
- cancelSleep = cancel;
171
+ if (isSubscribe && !lastError) return void 0;
172
+ throw lastError ?? new AccountRequestError("Account status is unavailable.", "invalid_response", "status", lastApi);
160
173
  });
161
- cancelSleep = null;
162
- }
163
- if (isStop) {
164
- return;
174
+ } catch (error) {
175
+ if (stopped) return void 0;
176
+ if (error instanceof ApiError && error.code === "timeout" && !(error instanceof AccountRequestError)) {
177
+ if (isSubscribe && !lastError) return void 0;
178
+ error = lastError ?? new AccountRequestError("Account request timed out.", "timeout", lastStage, lastApi);
179
+ }
180
+ if (!(error instanceof ApiError && error.code === "aborted")) failCallback == null ? void 0 : failCallback();
181
+ throw error;
182
+ } finally {
183
+ signal == null ? void 0 : signal.removeEventListener("abort", cancel);
165
184
  }
166
- failCallback == null ? void 0 : failCallback();
167
- throw new Error("get user profile error");
168
- }
169
- function sleep(ms = 3e3, onCancel) {
170
- return new Promise((resolve) => {
171
- const id = setTimeout(resolve, ms);
172
- onCancel == null ? void 0 : onCancel(() => {
173
- clearTimeout(id);
174
- resolve();
175
- });
176
- });
177
185
  }
178
186
  export {
179
187
  computeAvailableLimit,