yichong-canva2 1.1.27 → 1.1.28
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 +98 -65
- package/dist/api/error.js +12 -0
- package/dist/api/predictions.js +31 -0
- package/dist/api/request.js +126 -0
- package/dist/index.js +2 -0
- package/dist/login/context.js +7 -0
- package/dist/login/login/login.js +9 -37
- package/dist/login/privider.js +15 -6
- package/dist/login/use_canva.js +1 -1
- package/dist/types/api/error.d.ts +7 -0
- package/dist/types/api/index.d.ts +2 -0
- package/dist/types/api/predictions.d.ts +4 -0
- package/dist/types/api/request.d.ts +15 -0
- package/dist/types/api/types.d.ts +43 -0
- package/dist/types/index.d.ts +1 -0
- package/dist/types/login/context.d.ts +2 -1
- package/dist/types/login/index.d.ts +1 -0
- package/dist/types/login/privider.d.ts +5 -1
- package/package.json +9 -5
package/README.md
CHANGED
|
@@ -1,65 +1,98 @@
|
|
|
1
|
-
# yichong-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
##
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
}
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
1
|
+
# yichong-canva2
|
|
2
|
+
|
|
3
|
+
使用一个 `YiChongCanvaProvider` 管理登录、订阅和额度,通过 `useYiChongCanva()` 调用后端同名接口。
|
|
4
|
+
|
|
5
|
+
## 使用
|
|
6
|
+
|
|
7
|
+
```tsx
|
|
8
|
+
import { useState } from "react";
|
|
9
|
+
import { YiChongCanvaProvider, useYiChongCanva } from "yichong-canva2";
|
|
10
|
+
|
|
11
|
+
function App() {
|
|
12
|
+
return (
|
|
13
|
+
<YiChongCanvaProvider
|
|
14
|
+
appId="YOUR_CANVA_APP_ID"
|
|
15
|
+
productName="your_app_channel"
|
|
16
|
+
baseUrl="https://usa.imgkits.com/your_app_channel"
|
|
17
|
+
version={1}
|
|
18
|
+
>
|
|
19
|
+
<GenerateButton />
|
|
20
|
+
</YiChongCanvaProvider>
|
|
21
|
+
);
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function GenerateButton() {
|
|
25
|
+
const client = useYiChongCanva();
|
|
26
|
+
const [error, setError] = useState("");
|
|
27
|
+
const [status, setStatus] = useState("");
|
|
28
|
+
const [busy, setBusy] = useState(false);
|
|
29
|
+
|
|
30
|
+
async function generate() {
|
|
31
|
+
setError("");
|
|
32
|
+
setBusy(true);
|
|
33
|
+
try {
|
|
34
|
+
const created = await client.createSpecifyPrediction({
|
|
35
|
+
owner: "openai",
|
|
36
|
+
name: "gpt-image-2",
|
|
37
|
+
input: { prompt: "a cat" },
|
|
38
|
+
});
|
|
39
|
+
const prediction = await client.getPrediction({ id: created.data });
|
|
40
|
+
setStatus(prediction.data.status);
|
|
41
|
+
// getPrediction 只查询一次;仍在运行时由应用决定继续查询的时机。
|
|
42
|
+
if (prediction.data.status === "failed") {
|
|
43
|
+
setError(prediction.data.error_msg || prediction.data.error || "Generation failed");
|
|
44
|
+
}
|
|
45
|
+
} catch (error) {
|
|
46
|
+
setError(error instanceof Error ? error.message : "Request failed");
|
|
47
|
+
} finally {
|
|
48
|
+
setBusy(false);
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
return <>
|
|
53
|
+
<button disabled={client.loginStatus !== "success" || busy} onClick={() => void generate()}>Generate</button>
|
|
54
|
+
{status && <p>{status}</p>}
|
|
55
|
+
{error && <p role="alert">{error}</p>}
|
|
56
|
+
</>;
|
|
57
|
+
}
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
`baseUrl` 沿用原有账户扣费接口的地址。AI 请求默认使用 `https://api.imgkits.com`,可以通过可选的 `apiBaseUrl` 指定测试地址。
|
|
61
|
+
|
|
62
|
+
语言默认在每次请求时读取 `document.documentElement.lang` 或浏览器语言;应用有自己的国际化状态时,在 Provider 上传 `getLocale={() => currentLocale}`。
|
|
63
|
+
|
|
64
|
+
## 后端接口
|
|
65
|
+
|
|
66
|
+
| 调用 | 后端路径 | 成功响应 |
|
|
67
|
+
| --- | --- | --- |
|
|
68
|
+
| `client.createSpecifyPrediction({ owner, name, input })` | `POST /replicate/createSpecifyPrediction` | `{ code: 0, msg: "ok", data: "任务 ID" }` |
|
|
69
|
+
| `client.getPrediction({ id })` | `POST /replicate/getPrediction` | `{ code: 0, msg: "ok", data: { id, status, output, ... } }` |
|
|
70
|
+
|
|
71
|
+
Provider 自动注入 query 中的 `uid`、`platform_uid`、`platform=canva_addon`、`app_channel`,以及请求头 `Authorization: Bearer <jwt>`、`Channel: ai`、`Accept-Language`。创建请求中的 `user_id` 使用系统用户 ID(`userStatus.profile.id`)。调用方无需维护这些字段。
|
|
72
|
+
|
|
73
|
+
当前创建接口支持普通的 `owner/name/input` 合同;视频 `schema_v2` 等高级参数后续接入。模型参数按 JSON 原样发送,不改写 prompt 或供应商。两种方法都只发送一次请求,不自动轮询、重试创建、扣费或插入 Canva 设计。原有登录、额度和结账会话方法继续由同一个 hook 提供。
|
|
74
|
+
|
|
75
|
+
HTTP 失败、后端 `code` 非 `0`、网络错误、无效响应、超时和取消都会抛出导出的 `ApiError`。服务端返回的 `msg` 保留在 `error.message` / `error.userMessage`,应用应在错误组件中直接展示。`code=0` 且 `data.status="failed"` 表示任务执行失败,查询方法会保留任务信息,应用应处理 `error_msg` / `error`。
|
|
76
|
+
|
|
77
|
+
```ts
|
|
78
|
+
const controller = new AbortController();
|
|
79
|
+
const prediction = await client.getPrediction(
|
|
80
|
+
{ id: taskId },
|
|
81
|
+
{ signal: controller.signal, timeoutMs: 30_000 },
|
|
82
|
+
);
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
取消只终止当前 HTTP 等待,不会取消已经创建的后端任务。默认请求超时为 60 秒,包含读取响应正文的时间。
|
|
86
|
+
|
|
87
|
+
## 开发
|
|
88
|
+
|
|
89
|
+
```bash
|
|
90
|
+
npm ci
|
|
91
|
+
npm run lint:types
|
|
92
|
+
npm run lint
|
|
93
|
+
npm test
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
`npm test` 构建后使用 Node 测试真实产物,覆盖请求合同、错误、超时、取消,以及 Provider 登录/刷新后的凭据共享。测试替换 Canva 宿主和网络请求,不调用真实模型。
|
|
97
|
+
|
|
98
|
+
源码在 `packages/`,构建输出在 `dist/`。`npm run lint` 检查新增 API 模块和测试;全包类型由 `lint:types` 检查。原包的旧 Provider 实现暂时保留。
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { ApiError } from "./error.js";
|
|
2
|
+
import { isObject, isNonemptyString, invalid, postApi, validateJson } from "./request.js";
|
|
3
|
+
function createPredictionApi(getContext) {
|
|
4
|
+
return {
|
|
5
|
+
async createSpecifyPrediction(params, options) {
|
|
6
|
+
if (!isObject(params) || !isNonemptyString(params.owner) || !isNonemptyString(params.name) || !isObject(params.input)) {
|
|
7
|
+
invalid("createSpecifyPrediction requires owner, name and an input object.");
|
|
8
|
+
}
|
|
9
|
+
if (Object.keys(params).some((key) => !["owner", "name", "input"].includes(key))) {
|
|
10
|
+
invalid("createSpecifyPrediction currently supports owner, name and input only.");
|
|
11
|
+
}
|
|
12
|
+
validateJson(params);
|
|
13
|
+
const response = await postApi(getContext(), "createSpecifyPrediction", { owner: params.owner, name: params.name, input: params.input }, options);
|
|
14
|
+
if (!isNonemptyString(response.data)) throw new ApiError("Create response did not contain a prediction ID.", "invalid_response");
|
|
15
|
+
return response;
|
|
16
|
+
},
|
|
17
|
+
async getPrediction(params, options) {
|
|
18
|
+
if (!isObject(params) || !isNonemptyString(params.id) || Object.keys(params).some((key) => key !== "id")) {
|
|
19
|
+
invalid("getPrediction requires an id string.");
|
|
20
|
+
}
|
|
21
|
+
const response = await postApi(getContext(), "getPrediction", { id: params.id }, options);
|
|
22
|
+
if (!isObject(response.data) || !isNonemptyString(response.data.id) || !isNonemptyString(response.data.status)) {
|
|
23
|
+
throw new ApiError("Query response did not contain prediction information.", "invalid_response");
|
|
24
|
+
}
|
|
25
|
+
return response;
|
|
26
|
+
}
|
|
27
|
+
};
|
|
28
|
+
}
|
|
29
|
+
export {
|
|
30
|
+
createPredictionApi
|
|
31
|
+
};
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
import { ApiError } from "./error.js";
|
|
2
|
+
function isObject(value) {
|
|
3
|
+
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
4
|
+
}
|
|
5
|
+
function isNonemptyString(value) {
|
|
6
|
+
return typeof value === "string" && value.trim().length > 0;
|
|
7
|
+
}
|
|
8
|
+
function invalid(message) {
|
|
9
|
+
throw new ApiError(message, "invalid_request");
|
|
10
|
+
}
|
|
11
|
+
function validateJson(value, ancestors = /* @__PURE__ */ new Set()) {
|
|
12
|
+
if (value === null || typeof value === "string" || typeof value === "boolean") return;
|
|
13
|
+
if (typeof value === "number" && Number.isFinite(value)) return;
|
|
14
|
+
if (typeof value !== "object" || ancestors.has(value)) invalid("Parameters must contain non-circular JSON values.");
|
|
15
|
+
if (!Array.isArray(value) && Object.getPrototypeOf(value) !== Object.prototype && Object.getPrototypeOf(value) !== null) {
|
|
16
|
+
invalid("Parameters must contain plain JSON objects.");
|
|
17
|
+
}
|
|
18
|
+
ancestors.add(value);
|
|
19
|
+
for (const child of Object.values(value)) validateJson(child, ancestors);
|
|
20
|
+
ancestors.delete(value);
|
|
21
|
+
}
|
|
22
|
+
function language(getLocale) {
|
|
23
|
+
const value = (getLocale == null ? void 0 : getLocale()) || typeof document !== "undefined" && document.documentElement.lang || typeof navigator !== "undefined" && navigator.language || "en";
|
|
24
|
+
try {
|
|
25
|
+
return Intl.getCanonicalLocales(value.split(",")[0].split(";")[0].trim().replace(/_/g, "-"))[0] || "en";
|
|
26
|
+
} catch {
|
|
27
|
+
return "en";
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
async function postApi(context, method, params, options = {}) {
|
|
31
|
+
var _a, _b, _c, _d, _e;
|
|
32
|
+
const timeoutMs = options.timeoutMs ?? 6e4;
|
|
33
|
+
if (!Number.isInteger(timeoutMs) || timeoutMs <= 0 || timeoutMs > 2147483647) {
|
|
34
|
+
invalid("timeoutMs must be a positive integer in milliseconds.");
|
|
35
|
+
}
|
|
36
|
+
if ((_a = options.signal) == null ? void 0 : _a.aborted) throw new ApiError("Request canceled.", "aborted");
|
|
37
|
+
const { userStatus, productName, apiBaseUrl } = context;
|
|
38
|
+
const uid = (_b = userStatus.profile) == null ? void 0 : _b.id;
|
|
39
|
+
if (!isNonemptyString(uid) || !isNonemptyString(userStatus.userId) || !isNonemptyString(userStatus.jwt)) {
|
|
40
|
+
throw new ApiError("Sign in before calling prediction APIs.", "account_not_ready");
|
|
41
|
+
}
|
|
42
|
+
if (!isNonemptyString(productName)) invalid("productName is required.");
|
|
43
|
+
let url;
|
|
44
|
+
try {
|
|
45
|
+
url = new URL(apiBaseUrl);
|
|
46
|
+
} catch {
|
|
47
|
+
invalid("apiBaseUrl must be an absolute HTTP(S) URL.");
|
|
48
|
+
}
|
|
49
|
+
if (!["https:", "http:"].includes(url.protocol) || url.username || url.password || url.search || url.hash) {
|
|
50
|
+
invalid("apiBaseUrl must be HTTP(S) without credentials, query or fragment.");
|
|
51
|
+
}
|
|
52
|
+
url.pathname = `${url.pathname.replace(/\/+$/, "")}/replicate/${method}`;
|
|
53
|
+
url.searchParams.set("uid", uid);
|
|
54
|
+
url.searchParams.set("platform_uid", userStatus.userId);
|
|
55
|
+
url.searchParams.set("platform", "canva_addon");
|
|
56
|
+
url.searchParams.set("app_channel", productName);
|
|
57
|
+
const headers = {
|
|
58
|
+
"Content-Type": "application/json",
|
|
59
|
+
"Accept-Language": language(context.getLocale),
|
|
60
|
+
Authorization: `Bearer ${userStatus.jwt}`,
|
|
61
|
+
Channel: "ai"
|
|
62
|
+
};
|
|
63
|
+
const body = JSON.stringify(method === "createSpecifyPrediction" ? { ...params, user_id: uid } : params);
|
|
64
|
+
const controller = new AbortController();
|
|
65
|
+
let timedOut = false;
|
|
66
|
+
let rejectCanceled;
|
|
67
|
+
const canceled = new Promise((_, reject) => {
|
|
68
|
+
rejectCanceled = reject;
|
|
69
|
+
});
|
|
70
|
+
const cancel = () => {
|
|
71
|
+
controller.abort();
|
|
72
|
+
rejectCanceled(new ApiError(timedOut ? "Request timed out." : "Request canceled.", timedOut ? "timeout" : "aborted"));
|
|
73
|
+
};
|
|
74
|
+
(_c = options.signal) == null ? void 0 : _c.addEventListener("abort", cancel, { once: true });
|
|
75
|
+
const timer = setTimeout(() => {
|
|
76
|
+
timedOut = true;
|
|
77
|
+
cancel();
|
|
78
|
+
}, timeoutMs);
|
|
79
|
+
try {
|
|
80
|
+
return await Promise.race([
|
|
81
|
+
(async () => {
|
|
82
|
+
const response = await fetch(url.toString(), {
|
|
83
|
+
method: "POST",
|
|
84
|
+
headers,
|
|
85
|
+
body,
|
|
86
|
+
signal: controller.signal,
|
|
87
|
+
credentials: "omit",
|
|
88
|
+
redirect: "error"
|
|
89
|
+
});
|
|
90
|
+
let payload;
|
|
91
|
+
try {
|
|
92
|
+
payload = await response.json();
|
|
93
|
+
} catch {
|
|
94
|
+
throw new ApiError("Backend returned an invalid JSON response.", response.ok ? "invalid_response" : "http_error", response.status);
|
|
95
|
+
}
|
|
96
|
+
const message = isObject(payload) && isNonemptyString(payload.msg) ? payload.msg : "Backend request failed.";
|
|
97
|
+
const code = isObject(payload) && (typeof payload.code === "string" || typeof payload.code === "number") ? payload.code : "http_error";
|
|
98
|
+
if (!response.ok) throw new ApiError(message, code, response.status);
|
|
99
|
+
if (!isObject(payload) || typeof payload.code !== "number" && typeof payload.code !== "string") {
|
|
100
|
+
throw new ApiError("Backend returned an invalid response envelope.", "invalid_response", response.status);
|
|
101
|
+
}
|
|
102
|
+
if (payload.code !== 0) throw new ApiError(message, payload.code, response.status);
|
|
103
|
+
if (typeof payload.msg !== "string" || !Object.prototype.hasOwnProperty.call(payload, "data")) {
|
|
104
|
+
throw new ApiError("Backend returned an invalid response envelope.", "invalid_response", response.status);
|
|
105
|
+
}
|
|
106
|
+
return payload;
|
|
107
|
+
})(),
|
|
108
|
+
canceled
|
|
109
|
+
]);
|
|
110
|
+
} catch (error) {
|
|
111
|
+
if (timedOut) throw new ApiError("Request timed out.", "timeout");
|
|
112
|
+
if ((_d = options.signal) == null ? void 0 : _d.aborted) throw new ApiError("Request canceled.", "aborted");
|
|
113
|
+
if (error instanceof ApiError) throw error;
|
|
114
|
+
throw new ApiError("Unable to connect to the backend.", "network_error");
|
|
115
|
+
} finally {
|
|
116
|
+
clearTimeout(timer);
|
|
117
|
+
(_e = options.signal) == null ? void 0 : _e.removeEventListener("abort", cancel);
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
export {
|
|
121
|
+
invalid,
|
|
122
|
+
isNonemptyString,
|
|
123
|
+
isObject,
|
|
124
|
+
postApi,
|
|
125
|
+
validateJson
|
|
126
|
+
};
|
package/dist/index.js
CHANGED
|
@@ -1,7 +1,9 @@
|
|
|
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
5
|
export {
|
|
6
|
+
ApiError,
|
|
5
7
|
YiChongCanvaContext,
|
|
6
8
|
YiChongCanvaProvider,
|
|
7
9
|
useYiChongCanva
|
package/dist/login/context.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import React from "react";
|
|
2
|
+
import { ApiError } from "../api/error.js";
|
|
2
3
|
const YiChongCanvaContext = React.createContext(
|
|
3
4
|
{
|
|
4
5
|
userStatus: {},
|
|
@@ -28,6 +29,12 @@ const YiChongCanvaContext = React.createContext(
|
|
|
28
29
|
},
|
|
29
30
|
loginStatus: "idle",
|
|
30
31
|
manualLogin: () => {
|
|
32
|
+
},
|
|
33
|
+
createSpecifyPrediction: async () => {
|
|
34
|
+
throw new ApiError("Wrap your components in YiChongCanvaProvider first.", "provider_missing");
|
|
35
|
+
},
|
|
36
|
+
getPrediction: async () => {
|
|
37
|
+
throw new ApiError("Wrap your components in YiChongCanvaProvider first.", "provider_missing");
|
|
31
38
|
}
|
|
32
39
|
}
|
|
33
40
|
);
|
|
@@ -67,23 +67,6 @@ function isSubscribeChanged(current, baseline) {
|
|
|
67
67
|
}
|
|
68
68
|
return false;
|
|
69
69
|
}
|
|
70
|
-
/**
|
|
71
|
-
* 轮询获取用户资料/订阅状态
|
|
72
|
-
*
|
|
73
|
-
* @param {Object} options - 参数对象
|
|
74
|
-
* @param {number} [options.maxCount=50] - 最大轮询次数
|
|
75
|
-
* @param {number|function} [options.interval] - 每次轮询等待的间隔(ms),可以是函数
|
|
76
|
-
* @param {number} [options.maxDurationMs] - 最大轮询持续时间(ms)
|
|
77
|
-
* @param {string} options.productName - 产品名称
|
|
78
|
-
* @param {string} options.userId - 用户ID
|
|
79
|
-
* @param {function} [options.successCallback] - 轮询成功(获取到所需状态)时的回调
|
|
80
|
-
* @param {function} [options.failCallback] - 轮询失败时的回调
|
|
81
|
-
* @param {boolean} [options.isSubscribe=false] - 是否为订阅状态检测
|
|
82
|
-
* @param {*} [options.baseline] - 比较基准,用于判断订阅状态是否变化
|
|
83
|
-
* @param {function} [options.isChanged] - 判断状态变化的函数
|
|
84
|
-
* @param {function} [options.onStop] - 停止轮询回调(暴露终止方法)
|
|
85
|
-
* @returns {Promise<object>} 用户状态对象
|
|
86
|
-
*/
|
|
87
70
|
async function getUserProfile({
|
|
88
71
|
maxCount = 50,
|
|
89
72
|
interval,
|
|
@@ -98,42 +81,35 @@ async function getUserProfile({
|
|
|
98
81
|
onStop
|
|
99
82
|
}) {
|
|
100
83
|
var _a, _b;
|
|
101
|
-
let count = 0;
|
|
102
|
-
const startedAt = Date.now();
|
|
103
|
-
// 获取passport凭证
|
|
84
|
+
let count = 0;
|
|
85
|
+
const startedAt = Date.now();
|
|
104
86
|
let passportResult = await apis.getPassport(userId, productName);
|
|
105
87
|
let passport = (_a = passportResult.data) == null ? void 0 : _a.passport;
|
|
106
|
-
let isStop = false;
|
|
107
|
-
let cancelSleep = null;
|
|
108
|
-
let snapshot = baseline ?? null;
|
|
109
|
-
// 收到onStop通知时,终止轮询
|
|
88
|
+
let isStop = false;
|
|
89
|
+
let cancelSleep = null;
|
|
90
|
+
let snapshot = baseline ?? null;
|
|
110
91
|
onStop == null ? void 0 : onStop(() => {
|
|
111
92
|
isStop = true;
|
|
112
|
-
count = maxCount;
|
|
113
|
-
cancelSleep == null ? void 0 : cancelSleep();
|
|
93
|
+
count = maxCount;
|
|
94
|
+
cancelSleep == null ? void 0 : cancelSleep();
|
|
114
95
|
});
|
|
115
|
-
// 判断是否到达最大轮询次数或超时
|
|
116
96
|
const expired = () => count >= maxCount || maxDurationMs != null && Date.now() - startedAt >= maxDurationMs;
|
|
117
97
|
while (!expired()) {
|
|
118
98
|
console.log("poll", count);
|
|
119
99
|
let userStatus;
|
|
120
100
|
try {
|
|
121
|
-
// 查询passport对应的用户状态
|
|
122
101
|
userStatus = await (await apis.getUserStatusByPassport(passport, productName)).data;
|
|
123
102
|
} catch (e) {
|
|
124
103
|
userStatus = void 0;
|
|
125
104
|
}
|
|
126
105
|
if (userStatus == null ? void 0 : userStatus.profile) {
|
|
127
|
-
// 普通获取,无需订阅状态变化判断
|
|
128
106
|
if (!isSubscribe) {
|
|
129
107
|
successCallback == null ? void 0 : successCallback(userStatus);
|
|
130
108
|
return userStatus;
|
|
131
109
|
}
|
|
132
|
-
// 订阅状态获取
|
|
133
110
|
if (!snapshot) {
|
|
134
|
-
snapshot = takeSubscribeBaseline(userStatus);
|
|
111
|
+
snapshot = takeSubscribeBaseline(userStatus);
|
|
135
112
|
} else {
|
|
136
|
-
// 用isChanged或缺省方法进行状态对比
|
|
137
113
|
const changed = isChanged ? isChanged(userStatus, snapshot) : isSubscribeChanged(userStatus, snapshot);
|
|
138
114
|
if (changed) {
|
|
139
115
|
console.log("subscribe success");
|
|
@@ -142,22 +118,18 @@ async function getUserProfile({
|
|
|
142
118
|
}
|
|
143
119
|
}
|
|
144
120
|
} else if (userStatus) {
|
|
145
|
-
// (有返回但无profile) passport失效,移除缓存重新获取
|
|
146
121
|
localStorage.removeItem(userId + "_passport");
|
|
147
122
|
try {
|
|
148
123
|
passportResult = await apis.getPassport(userId, productName);
|
|
149
124
|
passport = (_b = passportResult.data) == null ? void 0 : _b.passport;
|
|
150
125
|
} catch (e) {
|
|
151
|
-
// 无需处理,继续重试
|
|
152
126
|
}
|
|
153
127
|
}
|
|
154
128
|
count++;
|
|
155
129
|
if (isStop || expired()) {
|
|
156
130
|
break;
|
|
157
131
|
}
|
|
158
|
-
// 计算下一次轮询的间隔
|
|
159
132
|
let ms = typeof interval === "function" ? interval() : interval ?? 3e3;
|
|
160
|
-
// 距离最大允许持续时间的剩余时间也必须纳入约束
|
|
161
133
|
if (maxDurationMs != null) {
|
|
162
134
|
ms = Math.min(ms, Math.max(maxDurationMs - (Date.now() - startedAt), 0));
|
|
163
135
|
}
|
|
@@ -167,7 +139,7 @@ async function getUserProfile({
|
|
|
167
139
|
cancelSleep = null;
|
|
168
140
|
}
|
|
169
141
|
if (isStop) {
|
|
170
|
-
return;
|
|
142
|
+
return;
|
|
171
143
|
}
|
|
172
144
|
failCallback == null ? void 0 : failCallback();
|
|
173
145
|
throw new Error("get user profile error");
|
package/dist/login/privider.js
CHANGED
|
@@ -4,6 +4,7 @@ import { handleLogin, takeSubscribeBaseline, getUserProfile } from "./login/logi
|
|
|
4
4
|
import { YiChongCanvaContext } from "./context.js";
|
|
5
5
|
import _ from "lodash";
|
|
6
6
|
import { getAppVersion } from "./version.js";
|
|
7
|
+
import { createPredictionApi } from "../api/predictions.js";
|
|
7
8
|
function reduceFreeTimes(baseUrl, passport, cnt = 1) {
|
|
8
9
|
const header = {
|
|
9
10
|
"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
|
|
@@ -41,6 +42,8 @@ const YiChongCanvaProvider = ({
|
|
|
41
42
|
onUpdateUserStatus,
|
|
42
43
|
// freeTimes = 1,
|
|
43
44
|
baseUrl,
|
|
45
|
+
apiBaseUrl = "https://api.imgkits.com",
|
|
46
|
+
getLocale,
|
|
44
47
|
autoLogin = true,
|
|
45
48
|
testMode: _testMode = "noTest",
|
|
46
49
|
version = 1,
|
|
@@ -59,6 +62,12 @@ const YiChongCanvaProvider = ({
|
|
|
59
62
|
const sessionStopRef = useRef(null);
|
|
60
63
|
const [loginStatus, setLoginStatus] = useState("idle");
|
|
61
64
|
const userStatusRef = useRef({});
|
|
65
|
+
const apiConfigRef = useRef({ apiBaseUrl, productName, getLocale });
|
|
66
|
+
apiConfigRef.current = { apiBaseUrl, productName, getLocale };
|
|
67
|
+
const [predictionApi] = useState(() => createPredictionApi(() => ({
|
|
68
|
+
...apiConfigRef.current,
|
|
69
|
+
userStatus: userStatusRef.current
|
|
70
|
+
})));
|
|
62
71
|
useEffect(() => {
|
|
63
72
|
userStatusRef.current = userStatus;
|
|
64
73
|
}, [userStatus]);
|
|
@@ -88,9 +97,9 @@ const YiChongCanvaProvider = ({
|
|
|
88
97
|
}
|
|
89
98
|
};
|
|
90
99
|
}
|
|
91
|
-
const new_user = _.merge({},
|
|
92
|
-
if (JSON.stringify(new_user) !== JSON.stringify(
|
|
93
|
-
|
|
100
|
+
const new_user = _.merge({}, userStatusRef.current, user);
|
|
101
|
+
if (JSON.stringify(new_user) !== JSON.stringify(userStatusRef.current)) {
|
|
102
|
+
userStatusRef.current = new_user;
|
|
94
103
|
setUserStatus(new_user);
|
|
95
104
|
}
|
|
96
105
|
};
|
|
@@ -177,9 +186,9 @@ const YiChongCanvaProvider = ({
|
|
|
177
186
|
},
|
|
178
187
|
successCallback(u) {
|
|
179
188
|
u.userId = userId;
|
|
189
|
+
updateUserStatus(u);
|
|
180
190
|
finish(u);
|
|
181
191
|
onUpdateUserStatus == null ? void 0 : onUpdateUserStatus(u);
|
|
182
|
-
updateUserStatus(u);
|
|
183
192
|
}
|
|
184
193
|
}).catch(() => {
|
|
185
194
|
console.log("checkout session ttl reached");
|
|
@@ -398,10 +407,9 @@ const YiChongCanvaProvider = ({
|
|
|
398
407
|
userId: (window == null ? void 0 : window.userId) || "",
|
|
399
408
|
maxCount: 2,
|
|
400
409
|
successCallback(userStatus2) {
|
|
401
|
-
console.log("refreshUserStatus", userStatus2);
|
|
402
410
|
userStatus2.userId = (window == null ? void 0 : window.userId) || "";
|
|
403
|
-
onUpdateUserStatus == null ? void 0 : onUpdateUserStatus(userStatus2);
|
|
404
411
|
updateUserStatus(userStatus2);
|
|
412
|
+
onUpdateUserStatus == null ? void 0 : onUpdateUserStatus(userStatus2);
|
|
405
413
|
resolve(userStatus2);
|
|
406
414
|
}
|
|
407
415
|
}).catch(() => {
|
|
@@ -556,6 +564,7 @@ const YiChongCanvaProvider = ({
|
|
|
556
564
|
YiChongCanvaContext.Provider,
|
|
557
565
|
{
|
|
558
566
|
value: {
|
|
567
|
+
...predictionApi,
|
|
559
568
|
userStatus,
|
|
560
569
|
updateUserStatus,
|
|
561
570
|
handleLogin: login,
|
package/dist/login/use_canva.js
CHANGED
|
@@ -3,7 +3,7 @@ import { YiChongCanvaContext } from "./context.js";
|
|
|
3
3
|
const useYiChongCanva = () => {
|
|
4
4
|
const context = useContext(YiChongCanvaContext);
|
|
5
5
|
if (!context) {
|
|
6
|
-
throw new Error("
|
|
6
|
+
throw new Error("useYiChongCanva must be used within YiChongCanvaProvider");
|
|
7
7
|
}
|
|
8
8
|
return context;
|
|
9
9
|
};
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
/** message / userMessage 保留服务端翻译后的 msg,供应用展示。 */
|
|
2
|
+
export declare class ApiError extends Error {
|
|
3
|
+
readonly code: string | number;
|
|
4
|
+
readonly status?: number | undefined;
|
|
5
|
+
readonly userMessage: string;
|
|
6
|
+
constructor(message: string, code: string | number, status?: number | undefined);
|
|
7
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { UserStatus } from '../login/interface';
|
|
2
|
+
import { ApiRequestOptions, ApiResponse, JsonObject } from './types';
|
|
3
|
+
/** 内部读取 Provider 的当前状态,不从 window / localStorage 读取 API 凭据。 */
|
|
4
|
+
export interface ApiContext {
|
|
5
|
+
userStatus: UserStatus;
|
|
6
|
+
productName: string;
|
|
7
|
+
apiBaseUrl: string;
|
|
8
|
+
getLocale?: () => string;
|
|
9
|
+
}
|
|
10
|
+
export declare function isObject(value: unknown): value is Record<string, unknown>;
|
|
11
|
+
export declare function isNonemptyString(value: unknown): value is string;
|
|
12
|
+
export declare function invalid(message: string): never;
|
|
13
|
+
/** 防止 stringify 悄悄删掉 undefined / 函数,或把 NaN / Infinity 转成 null。 */
|
|
14
|
+
export declare function validateJson(value: unknown, ancestors?: Set<object>): void;
|
|
15
|
+
export declare function postApi<T>(context: ApiContext, method: "createSpecifyPrediction" | "getPrediction", params: JsonObject, options?: ApiRequestOptions): Promise<ApiResponse<T>>;
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
export type JsonValue = string | number | boolean | null | JsonValue[] | JsonObject;
|
|
2
|
+
export type JsonObject = {
|
|
3
|
+
[key: string]: JsonValue;
|
|
4
|
+
};
|
|
5
|
+
/** 身份、渠道和鉴权由 Provider 注入,业务只传模型参数。 */
|
|
6
|
+
export interface CreateSpecifyPredictionParams {
|
|
7
|
+
owner: string;
|
|
8
|
+
name: string;
|
|
9
|
+
input: JsonObject;
|
|
10
|
+
}
|
|
11
|
+
export interface GetPredictionParams {
|
|
12
|
+
id: string;
|
|
13
|
+
}
|
|
14
|
+
/** 保留后端响应结构;HTTP 或 code 非 0 时抛出 ApiError。 */
|
|
15
|
+
export interface ApiResponse<T> {
|
|
16
|
+
code: 0;
|
|
17
|
+
msg: string;
|
|
18
|
+
data: T;
|
|
19
|
+
}
|
|
20
|
+
export interface Prediction {
|
|
21
|
+
id: string;
|
|
22
|
+
/** 常见值:starting / processing / succeeded / failed / canceled。 */
|
|
23
|
+
status: string;
|
|
24
|
+
output?: JsonValue;
|
|
25
|
+
error?: string | null;
|
|
26
|
+
error_msg?: string | null;
|
|
27
|
+
$platform?: string;
|
|
28
|
+
$model?: string;
|
|
29
|
+
/** 平台附加字段原样保留。 */
|
|
30
|
+
[key: string]: unknown;
|
|
31
|
+
}
|
|
32
|
+
export interface ApiRequestOptions {
|
|
33
|
+
/** 取消当前 HTTP 等待,不会取消已经创建的后端任务。 */
|
|
34
|
+
signal?: AbortSignal;
|
|
35
|
+
/** 单次请求超时,含响应正文读取;默认 60000 毫秒。 */
|
|
36
|
+
timeoutMs?: number;
|
|
37
|
+
}
|
|
38
|
+
export interface PredictionApi {
|
|
39
|
+
/** 只创建任务,data 是任务 ID;不会自动轮询或扣费。 */
|
|
40
|
+
createSpecifyPrediction(params: CreateSpecifyPredictionParams, options?: ApiRequestOptions): Promise<ApiResponse<string>>;
|
|
41
|
+
/** 只查询一次;code=0 且 status=failed 仍返回任务信息。 */
|
|
42
|
+
getPrediction(params: GetPredictionParams, options?: ApiRequestOptions): Promise<ApiResponse<Prediction>>;
|
|
43
|
+
}
|
package/dist/types/index.d.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { default as React } from 'react';
|
|
2
|
+
import { PredictionApi } from '../api/types';
|
|
2
3
|
import { canUseError, CheckoutSessionOptions, TestMode, UserStatus } from './interface';
|
|
3
4
|
/**
|
|
4
5
|
*
|
|
@@ -16,7 +17,7 @@ import { canUseError, CheckoutSessionOptions, TestMode, UserStatus } from './int
|
|
|
16
17
|
* @property {() => string} getPricingLink 获取付费链接
|
|
17
18
|
* @property {() => void} updateTestMode 更新测试模式, 只有在开发环境下有效
|
|
18
19
|
*/
|
|
19
|
-
export interface YiChongCanvaContextType {
|
|
20
|
+
export interface YiChongCanvaContextType extends PredictionApi {
|
|
20
21
|
userStatus: UserStatus;
|
|
21
22
|
updateUserStatus: (user: Partial<UserStatus>) => void;
|
|
22
23
|
handleLogin: () => void;
|
|
@@ -16,6 +16,10 @@ export interface YiChongCanvaProviderProps {
|
|
|
16
16
|
productName: string;
|
|
17
17
|
onUpdateUserStatus?: (userStatus: UserStatus) => void;
|
|
18
18
|
baseUrl: string;
|
|
19
|
+
/** AI 接口地址;baseUrl 仍用于原有账户扣费接口。 */
|
|
20
|
+
apiBaseUrl?: string;
|
|
21
|
+
/** 每次 API 请求读取当前界面语言,默认使用浏览器语言。 */
|
|
22
|
+
getLocale?: () => string;
|
|
19
23
|
autoLogin?: boolean;
|
|
20
24
|
testMode?: TestMode;
|
|
21
25
|
version: number;
|
|
@@ -35,4 +39,4 @@ export interface YiChongCanvaProviderProps {
|
|
|
35
39
|
* @param {string} params0.mode 测试模式
|
|
36
40
|
* @returns
|
|
37
41
|
*/
|
|
38
|
-
export declare const YiChongCanvaProvider: ({ children, appId, productName, onUpdateUserStatus, baseUrl, autoLogin, testMode: _testMode, version, mode, retry, maxAvailablePoints, }: YiChongCanvaProviderProps) => React.JSX.Element;
|
|
42
|
+
export declare const YiChongCanvaProvider: ({ children, appId, productName, onUpdateUserStatus, baseUrl, apiBaseUrl, getLocale, 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": "1.1.
|
|
3
|
+
"version": "1.1.28",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"main": "./dist/index.js",
|
|
6
6
|
"module": "./dist/index.js",
|
|
@@ -17,15 +17,19 @@
|
|
|
17
17
|
"scripts": {
|
|
18
18
|
"dev": "vite",
|
|
19
19
|
"build": "vite build",
|
|
20
|
-
"lint": "eslint
|
|
21
|
-
"
|
|
22
|
-
"
|
|
20
|
+
"lint": "eslint packages/api tests",
|
|
21
|
+
"lint:types": "tsc --noEmit",
|
|
22
|
+
"test": "npm run build && node --test --import ./tests/register.mjs tests/*.test.mjs",
|
|
23
|
+
"preview": "vite preview"
|
|
23
24
|
},
|
|
24
25
|
"peerDependencies": {
|
|
25
26
|
"@canva/user": ">=2.1.0",
|
|
26
27
|
"react": ">=18",
|
|
27
28
|
"react-dom": ">=18"
|
|
28
29
|
},
|
|
30
|
+
"dependencies": {
|
|
31
|
+
"lodash": "^4.17.21"
|
|
32
|
+
},
|
|
29
33
|
"devDependencies": {
|
|
30
34
|
"@canva/user": "^2.2.0",
|
|
31
35
|
"@eslint/js": "^9.21.0",
|
|
@@ -38,9 +42,9 @@
|
|
|
38
42
|
"eslint-plugin-react-hooks": "^5.1.0",
|
|
39
43
|
"eslint-plugin-react-refresh": "^0.4.19",
|
|
40
44
|
"globals": "^15.15.0",
|
|
41
|
-
"lodash": "^4.17.21",
|
|
42
45
|
"react": "18.3.1",
|
|
43
46
|
"react-dom": "18.3.1",
|
|
47
|
+
"react-test-renderer": "18.3.1",
|
|
44
48
|
"rollup-plugin-terser": "^7.0.2",
|
|
45
49
|
"typescript": "~5.7.3",
|
|
46
50
|
"typescript-eslint": "^8.24.1",
|