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.
@@ -1,25 +1,30 @@
1
- import requestUrl from "./login/apis/request.js";
2
- function getAppVersion(key, context) {
1
+ import { language, addContextQuery } from "../api/request.js";
2
+ import { withRequest } from "../api/transport.js";
3
+ import { ApiError } from "../api/error.js";
4
+ function getAppVersion(key, context, options = {}) {
3
5
  const myHeaders = new Headers();
4
- myHeaders.append("User-Agent", "Apifox/1.0.0 (https://apifox.com)");
5
6
  myHeaders.append("Accept", "*/*");
6
- myHeaders.append("Host", "usa.imgkits.com");
7
- myHeaders.append("Connection", "keep-alive");
8
7
  myHeaders.append("Content-Type", "application/x-www-form-urlencoded");
8
+ myHeaders.append("Accept-Language", language(context == null ? void 0 : context.getLocale));
9
9
  const urlencoded = new URLSearchParams();
10
10
  urlencoded.append("key", key);
11
- const requestOptions = {
12
- method: "POST",
13
- headers: myHeaders,
14
- body: urlencoded,
15
- redirect: "follow"
16
- };
17
- return requestUrl({ ...requestOptions, url: "https://usa.imgkits.com/site/get" }, context).then((res) => {
18
- if (!(res == null ? void 0 : res.success)) {
19
- return {};
20
- } else {
21
- return JSON.parse(res.data.value);
22
- }
11
+ return withRequest({ ...options, timeoutMs: options.timeoutMs ?? 1e4 }, async (signal) => {
12
+ const url = new URL("https://usa.imgkits.com/site/get");
13
+ if (context) addContextQuery(url, context);
14
+ const response = await fetch(url.toString(), {
15
+ method: "POST",
16
+ headers: myHeaders,
17
+ body: urlencoded,
18
+ credentials: "omit",
19
+ redirect: "error",
20
+ signal
21
+ });
22
+ if (!response.ok) throw new ApiError("Version configuration is unavailable.", "http_error", response.status);
23
+ const body = await response.json();
24
+ if (!(body == null ? void 0 : body.success)) return {};
25
+ const value = JSON.parse(body.data.value);
26
+ if (!value || typeof value !== "object" || !("version" in value) || typeof value.version !== "number" || !Number.isFinite(value.version)) return {};
27
+ return { version: value.version };
23
28
  });
24
29
  }
25
30
  export {
@@ -24,3 +24,5 @@ export declare class ApiError extends Error {
24
24
  retryAfter?: number;
25
25
  });
26
26
  }
27
+ /** 仅识别主动取消;普通 DOMException(例如 SecurityError)或后端任务失败不应被静默忽略。 */
28
+ export declare function isAbortError(error: unknown): boolean;
@@ -3,5 +3,6 @@
3
3
  * 实现工厂保持内部使用,业务通过 Provider 的 client 调用方法,共享登录身份和配置。
4
4
  * 参数、返回值及方法的 JSDoc 定义在 types.ts,会随声明文件发布供编辑器提示。
5
5
  */
6
- export { ApiError } from './error';
7
- export type { ApiRequestOptions, ApiResponse, ChatApi, ChatParams, ChatPayload, ChatResult, CreateVttParams, CreateVttResult, GetVttStatusParams, VttApi, VttStatusResult, VttTaskState, CompleteUploadParams, CompleteUploadResponse, ContentExtractParams, ContentExtractResult, ContentExtractionApi, TextCheckParams, CreateSpecifyPredictionParams, ErrorReportingApi, ErrorReportSource, GetPredictionParams, GeneratePresignedUrlParams, GetUploadUrlParams, InitiateUploadParams, InitiateUploadResponse, JsonObject, JsonValue, Prediction, PredictionApi, ReportErrorParams, ReportErrorResult, PresignedUrlResponse, TextModerationApi, TextModerationCategory, TextModerationDecision, TextModerationResult, UploadApi, UploadFileParams, UploadFileResult, UploadedPart, UploadPartUrlResponse, UploadProgress, UsageApi, UsageParams, UsageResponse, } from './types';
6
+ export { ApiError, isAbortError } from './error';
7
+ export { getPredictionOutputUrl } from './predictions';
8
+ export type { ApiRequestOptions, ApiResponse, CancelPredictionResponse, ChatApi, ChatParams, ChatPayload, ChatResult, CreateTextToSpeechParams, CreateTextToSpeechResult, GetTextToSpeechResultParams, TextToSpeechApi, TextToSpeechResult, TextToSpeechTaskState, CreateVttParams, CreateVttResult, GetVttStatusParams, VttApi, VttStatusResult, VttTaskState, CompleteUploadParams, CompleteUploadResponse, ContentExtractParams, ContentExtractResult, ContentExtractionApi, TextCheckParams, CreateSpecifyPredictionParams, ErrorReportingApi, ErrorReportSource, GetPredictionParams, GeneratePresignedUrlParams, GetUploadUrlParams, InitiateUploadParams, InitiateUploadResponse, JsonObject, JsonValue, Prediction, PredictionApi, WaitForPredictionOptions, ReportErrorParams, ReportUsageParams, UsageReportingApi, UsageReportingConfig, ReportErrorResult, PresignedUrlResponse, TextModerationApi, TextModerationCategory, TextModerationDecision, TextModerationResult, UploadApi, UploadFileParams, UploadFileResult, UploadedPart, UploadPartUrlResponse, UploadProgress, UsageApi, UsageParams, UsageResponse, } from './types';
@@ -1,8 +1,13 @@
1
1
  import { ApiContext } from './request';
2
2
  import { PredictionApi } from './types';
3
3
  /**
4
- * 将后端同名的任务创建/查询接口绑定到 Provider,保留参数名与原始响应结构。
5
- * 创建仅返回任务 ID,查询仅取得一次状态;轮询间隔、取消业务与结果展示由应用编排。
6
- * 两种调用都只发送一次请求,不自动重试、审核输入或记录消费,避免重复创建/扣费。
4
+ * 从 URL 字符串、嵌套数组或 { url } 中取得第一个有效 HTTP(S) 地址,没有则返回空字符串。
5
+ * 不把文本输出、blob:/data: 或其它模型元数据当图片链接;调用者仍需按模型检查资源类型。
6
+ */
7
+ export declare function getPredictionOutputUrl(output: unknown): string;
8
+ /**
9
+ * 将后端同名的任务创建/查询/取消接口绑定到 Provider,保留参数名与原始响应结构。
10
+ * 原始方法各请求一次;waitForPrediction 是显式调用的等待流程,仅安全地重试有限次状态查询。
11
+ * 不审核输入、创建额外任务或记录消费;停止等待不会自动取消后端任务。
7
12
  */
8
13
  export declare function createPredictionApi(getContext: () => ApiContext): PredictionApi;
@@ -1,6 +1,6 @@
1
1
  import { UserStatus } from '../login/interface';
2
2
  import { ApiError } from './error';
3
- import { ApiRequestOptions, ApiResponse, JsonObject } from './types';
3
+ import { ApiRequestOptions, ApiResponse, CancelPredictionResponse, JsonObject } from './types';
4
4
  /**
5
5
  * 各服务共用的调用上下文,由 Provider 在调用时提供当前快照。
6
6
  * 身份来自已完成的登录流程,不从 window / localStorage 搜索或猜测 API 凭据。
@@ -18,11 +18,14 @@ export interface ApiContext extends CommonRequestContext {
18
18
  declare const apiPaths: {
19
19
  readonly createSpecifyPrediction: "/replicate/createSpecifyPrediction";
20
20
  readonly getPrediction: "/replicate/getPrediction";
21
+ readonly cancelPrediction: "/replicate/cancelPrediction";
21
22
  readonly textCheck: "/api/public/text-moderation/check";
22
23
  readonly contentExtract: "/api/content-extract";
23
24
  readonly chat: "/api/chat";
24
25
  readonly createVtt: "/get-vtt/create";
25
26
  readonly getVttStatus: "/get-vtt/status";
27
+ readonly createTextToSpeech: "/api/text-to-speech/create";
28
+ readonly getTextToSpeechResult: "/api/text-to-speech/result";
26
29
  };
27
30
  /** 粗筛非空、非数组对象;是否属于普通 JSON 对象由 validateJson 进一步判断。 */
28
31
  export declare function isObject(value: unknown): value is Record<string, unknown>;
@@ -64,10 +67,12 @@ export declare function readJson(response: Response): Promise<unknown>;
64
67
  */
65
68
  export declare function backendError(response: Response, payload: unknown, fallbackCode: string | number): ApiError;
66
69
  /**
67
- * AI 接口的公共 POST:注入 Bearer JWT、Channel、语言与通用 query,并校验响应包。
70
+ * AI 接口的公共 POST:注入鉴权、Channel、语言与通用 query,并校验响应包。
71
+ * 旧 TTS 路由的 JWT 可选,其余保持原有 JWT 要求;账户归属不等于服务端身份验证。
68
72
  * 返回后端的 { code, msg, data },不提取/重命名 data;具体 API 再验证自己的业务数据。
69
73
  * 只执行一次请求,超时/取消涵盖读取响应正文;credentials: omit 不依赖浏览器 Cookie。
70
74
  * 禁止重定向,避免认证头被带往配置以外的跳转目标。
71
75
  */
72
- export declare function postApi<T>(context: ApiContext, method: keyof typeof apiPaths, params: JsonObject, options?: ApiRequestOptions): Promise<ApiResponse<T>>;
76
+ export declare function postApi(context: ApiContext, method: "cancelPrediction", params: JsonObject, options?: ApiRequestOptions): Promise<CancelPredictionResponse>;
77
+ export declare function postApi<T>(context: ApiContext, method: Exclude<keyof typeof apiPaths, "cancelPrediction">, params: JsonObject, options?: ApiRequestOptions): Promise<ApiResponse<T>>;
73
78
  export {};
@@ -0,0 +1,8 @@
1
+ import { ApiContext } from './request';
2
+ import { TextToSpeechApi } from './types';
3
+ /**
4
+ * 封装现有异步 TTS 创建/查询协议;仅请求一次,不附加轮询、重试或额外消费。
5
+ * guid 由请求层使用当前系统 uid 注入,调用方不能覆盖 guid 或改变计费分支的 app_id。
6
+ * 语音、语言与上游模型的默认选择继续由后端负责;SDK 不维护会过时的语音枚举。
7
+ */
8
+ export declare function createTextToSpeechApi(getContext: () => ApiContext): TextToSpeechApi;
@@ -126,11 +126,11 @@ export interface ApiResponse<T> {
126
126
  /** 对应接口的数据,不会被 SDK 解包或重命名。 */
127
127
  data: T;
128
128
  }
129
- /** 一次查询取得的任务快照;轮询频率、终态处理和结果展示由应用组织。 */
129
+ /** 一次查询取得的任务快照;可单次查询,也可交给 waitForPrediction 等待完成。 */
130
130
  export interface Prediction {
131
131
  /** 任务 ID。 */
132
132
  id: string;
133
- /** 常见值:starting / processing / succeeded / failed / canceled。 */
133
+ /** 常见值:starting / processing / succeeded / failed / canceled / aborted。 */
134
134
  status: string;
135
135
  /** 模型输出;可能是 URL、数组或对象,需按所选模型处理,不能一律当成图片 URL。 */
136
136
  output?: JsonValue;
@@ -155,6 +155,22 @@ export interface ApiRequestOptions {
155
155
  */
156
156
  timeoutMs?: number;
157
157
  }
158
+ /** 等待已创建的任务完成;不创建任务、不消费、不隐式调用后端取消。 */
159
+ export interface WaitForPredictionOptions extends ApiRequestOptions {
160
+ /** 两次查询之间的间隔,默认 3000 毫秒;允许 0,不在最后一次查询后继续等待。 */
161
+ intervalMs?: number;
162
+ /** 查询次数上限,默认 60;失败的查询也计入次数,必须为正整数。 */
163
+ maxPolls?: number;
164
+ /** 所有查询及间隔共用的总等待预算,默认 180000 毫秒;单次查询仍最多等待 60 秒。 */
165
+ timeoutMs?: number;
166
+ /**
167
+ * 默认 false,仅 succeeded 才成功。显式 true 时允许未结束任务已有 HTTP(S) 输出就返回,
168
+ * 供已确认支持提前输出的旧模型使用;failed/canceled/aborted 始终优先作为失败处理。
169
+ */
170
+ allowEarlyOutput?: boolean;
171
+ }
172
+ /** 后端取消接口存在两种原始响应;与 yichong-api 保持相同合同,不人为包装成 ok 布尔值。 */
173
+ export type CancelPredictionResponse = ApiResponse<Prediction> | Prediction;
158
174
  /** 指定模型的异步任务 API,业务流程可以用 restorePhoto 等业务函数组合这些原始方法。 */
159
175
  export interface PredictionApi {
160
176
  /**
@@ -174,6 +190,22 @@ export interface PredictionApi {
174
190
  * 应用自行安排下次查询并处理 succeeded / failed / canceled 等终态。
175
191
  */
176
192
  getPrediction(params: GetPredictionParams, options?: ApiRequestOptions): Promise<ApiResponse<Prediction>>;
193
+ /**
194
+ * 按 intervalMs 查询并返回成功的任务快照。默认只在 succeeded 时返回,输出由业务另行提取。
195
+ * failed/canceled/aborted 抛 prediction_failed,保留 error_msg 或 error;请求取消抛 aborted。
196
+ * 查询次数或总预算用完抛 prediction_timeout;临时网络/单次超时可继续,连续 3 次失败后保留原错误。
197
+ * HTTP、鉴权、业务错误直接抛出;不会重复创建、扣费或自动取消后端任务。
198
+ * @example
199
+ * const task = await client.waitForPrediction({ id }, { signal: controller.signal });
200
+ * const url = getPredictionOutputUrl(task.output);
201
+ */
202
+ waitForPrediction(params: GetPredictionParams, options?: WaitForPredictionOptions): Promise<Prediction>;
203
+ /**
204
+ * POST /replicate/cancelPrediction,只发送一次,默认超时 60 秒,保留后端原始响应。
205
+ * 失败抛 ApiError,由业务决定是否展示;各供应商的取消能力不同,不保证上游任务或费用立即停止。
206
+ * 取消前端等待与取消后端任务相互独立,waitForPrediction 不会自动调用本方法。
207
+ */
208
+ cancelPrediction(params: GetPredictionParams, options?: ApiRequestOptions): Promise<CancelPredictionResponse>;
177
209
  }
178
210
  /** 文本审核能力,与生成接口分开调用。 */
179
211
  export interface TextModerationApi {
@@ -324,11 +356,17 @@ export interface UploadFileParams {
324
356
  /** 目标桶,省略时使用 video;不会从文件 MIME 类型推断桶名。 */
325
357
  bucketName?: string;
326
358
  /**
327
- * 省略时生成 temp_{app_channel}_{YYYY-MM-DD}_{32位随机}.{后缀}。
359
+ * 省略时生成 {retention}_{app_channel}_{YYYY-MM-DD}_{32位随机}.{后缀},默认前缀 temp_。
328
360
  * 渠道取 Provider.productName,日期取本地日期;随机部分沿用旧应用 randomString(32) 的固定大小写字母/数字字符集。
329
- * 显式传入时使用该对象 key,不自动添加前缀或改名。
361
+ * 显式传入时使用该对象 key,不自动添加前缀或改名;不能与 retention 同时传入。
330
362
  */
331
363
  objectName?: string;
364
+ /**
365
+ * 自动命名的前缀,默认 temp;temp_ 对应现有 1 天规则,day30_ 对应 30 天规则。
366
+ * 只选择对象前缀,实际删除取决于目标桶的 R2 生命周期规则;普通/分片上传遵循同一规则。
367
+ * 与自定义 objectName 二选一,不能同时指定。
368
+ */
369
+ retention?: "temp" | "day30";
332
370
  /** true 时小文件也使用分片;省略或 false 时按文件大小选择。 */
333
371
  multipart?: boolean;
334
372
  /**
@@ -490,3 +528,99 @@ export interface VttApi {
490
528
  */
491
529
  getVttStatus(params: GetVttStatusParams, options?: ApiRequestOptions): Promise<ApiResponse<VttStatusResult>>;
492
530
  }
531
+ /** TTS 创建参数;仅保留后端的规范字段,系统 guid 由当前账户自动注入。 */
532
+ export interface CreateTextToSpeechParams {
533
+ /** 待合成文本,1 至 5000 个 Unicode 字符;保留原始空白,不自动裁剪或分段。 */
534
+ text: string;
535
+ /** 后端支持的语音 ID,例如 Arrogant_Miss;省略时由后端默认使用 alloy。 */
536
+ voice?: string;
537
+ /** 情感参数,例如 auto;不固定枚举,由后端及语音供应商判断是否支持。 */
538
+ emotion?: string;
539
+ /** 语速,0.5 至 2.0;省略时由后端使用 1.0,SDK 不自行舍入。 */
540
+ speed?: number;
541
+ /** 语言代码;省略时由后端识别文本语言,不从界面语言推断。 */
542
+ language?: string;
543
+ /** 可访问的 HTTP(S) 参考音频 URL;文件需先上传,不能直接传 File/Blob。 */
544
+ refer_audio?: string;
545
+ /**
546
+ * 参考音频对应的文本,最多 5000 个 Unicode 字符。
547
+ * 后端仅在 refer_audio 非空时使用;超过 5000 会被后端忽略,因此 SDK 提前拒绝超长值。
548
+ */
549
+ refer_audio_text?: string;
550
+ }
551
+ /** 使用创建响应中的 data.jobId 查询,不重复提交文本、语音或用户身份。 */
552
+ export interface GetTextToSpeechResultParams {
553
+ jobId: string;
554
+ }
555
+ /** TTS 任务快照;code=0 只代表接口成功,生成是否完成须检查 status。 */
556
+ export interface TextToSpeechTaskState {
557
+ /** 创建和查询响应都保留后端任务 ID。 */
558
+ jobId: string;
559
+ /** 常见值:-1 失败、0 排队、2 处理中、10 成功;兼容后端新增整数状态。 */
560
+ status: number;
561
+ /** 后端状态描述,例如 waiting、processing、done、fail。 */
562
+ status_str: string;
563
+ /** 任务失败原因,例如余额不足;排队或成功时可以为空。 */
564
+ remark?: string | null;
565
+ [key: string]: unknown;
566
+ }
567
+ /** 创建返回的任务状态;尚不包含音频结果,也可能立即返回 status=-1。 */
568
+ export type CreateTextToSpeechResult = TextToSpeechTaskState;
569
+ /** 查询返回的任务状态与音频结果;SDK 不改名、不下载、不自动插入设计。 */
570
+ export interface TextToSpeechResult extends TextToSpeechTaskState {
571
+ /** 后端生成的音频 URL;排队、处理中或失败时可以为 null 或空字符串。 */
572
+ result: string | null;
573
+ }
574
+ /** 异步文字转语音;保留现有 /api/text-to-speech 路径及 code/msg/data 响应包。 */
575
+ export interface TextToSpeechApi {
576
+ /**
577
+ * POST /api/text-to-speech/create,默认超时 60 秒,支持 signal 和 timeoutMs。
578
+ * 等待当前账户身份就绪,自动注入 guid 和通用 query;有有效 JWT 时附带 Bearer,无 JWT 时省略。
579
+ * 该旧接口本身未强制校验 JWT;query/guid 仅是归属字段,不应理解为服务端鉴权保证。
580
+ * 不接收 app_id/userId/guid 覆盖,不改变后端额度检查和用量记录,也不额外调用消费接口。
581
+ * 不重试、不轮询;超时/中止只停止客户端等待,后端可能已经创建任务。
582
+ * @example
583
+ * const task = await client.createTextToSpeech({ text: "你好", voice: "Arrogant_Miss", emotion: "auto" });
584
+ * const jobId = task.data.jobId;
585
+ */
586
+ createTextToSpeech(params: CreateTextToSpeechParams, options?: ApiRequestOptions): Promise<ApiResponse<CreateTextToSpeechResult>>;
587
+ /**
588
+ * POST /api/text-to-speech/result,默认超时 60 秒;只查询一次,由应用安排轮询及总时限。
589
+ * status=10 时读取 result;status=-1 时展示 remark。失败任务原样返回,不作为接口异常抛出。
590
+ */
591
+ getTextToSpeechResult(params: GetTextToSpeechResultParams, options?: ApiRequestOptions): Promise<ApiResponse<TextToSpeechResult>>;
592
+ }
593
+ /** 行为统计配置;独立于消费记账与飞书错误告警,关闭后不会发出埋点请求。 */
594
+ export interface UsageReportingConfig {
595
+ /** 默认 true;测试、预览或明确退出统计时可关闭。 */
596
+ enabled?: boolean;
597
+ /** 完整 GET 接口地址,默认 https://log.aibabygenerator.io/api/report;不附加固定路径。 */
598
+ endpoint?: string;
599
+ /** 统计后台的应用键;Canva 默认 {productName}_canva,公共客户端默认 {appChannel}_{platform}。 */
600
+ appKey?: string;
601
+ }
602
+ /** 仅传行为和少量统计属性;用户、应用、时间和事件 UUID 由客户端提供。 */
603
+ export interface ReportUsageParams {
604
+ /** 稳定事件名,例如 generate_start / generate_success;最多 64 字符,使用字母、数字、_、-、.、:。 */
605
+ sum_key: string;
606
+ /** 展示在统计后台的固定标题,不放用户输入,最多保留 128 字符。 */
607
+ title: string;
608
+ /**
609
+ * 少量统计属性,例如 operation_id、page、duration_ms、model、error_code。
610
+ * 不传提示词、完整 input、文件、资源地址、token 或异常对象;敏感字段和值会脱敏。
611
+ * 对象最多 3 层、30 个字段,数组最多 10 项,字符串最多 256 字符;最终 URL 最多 8192 字符。
612
+ */
613
+ data?: Record<string, unknown> | null;
614
+ }
615
+ /** 行为统计,不扣费、不刷新账户、不弹错误,也不会把自身失败转发到飞书。 */
616
+ export interface UsageReportingApi {
617
+ /**
618
+ * 兼容旧 GET /api/report 和 data 的双重 URL 编码;无需登录,不使用 JWT / passport。
619
+ * 返回是否收到 HTTP 成功确认,失败/关闭/取消/非法参数均返回 false,永不向业务抛错;可 void 调用。
620
+ * 默认每次请求最多 4 秒,网络/超时/429/5xx 最多重试一次,两次复用同一个事件 UUID;其他 4xx 不重试。
621
+ * options.timeoutMs 可缩短单次预算,最大 4000;signal 取消后不再重试。
622
+ * 服务端统计 timestamp 由 Worker 生成;客户端发生时间保存在 data.occurred_at。
623
+ * UUID 标识一次事件,data.operation_id 关联同一次业务流程,两者不能混用。
624
+ */
625
+ reportUsage(params: ReportUsageParams, options?: ApiRequestOptions): Promise<boolean>;
626
+ }
@@ -0,0 +1,16 @@
1
+ import { CommonRequestContext } from './request';
2
+ import { UsageReportingApi, UsageReportingConfig } from './types';
3
+ /** Provider 当前快照;账户尚未就绪也可调用,不通过登录校验或账户消费 API。 */
4
+ export interface UsageReportingContext extends CommonRequestContext {
5
+ usageReporting?: UsageReportingConfig;
6
+ /** Provider 提供 session_id/app_version 等基础属性,业务不能覆盖同名字段。 */
7
+ metadata?: Record<string, unknown>;
8
+ /** 已知凭据只参与脱敏,绝不发送至统计接口。 */
9
+ secrets?: readonly string[];
10
+ }
11
+ /**
12
+ * 兼容已有图片 GET 统计接口,改用 fetch 读取 HTTP 确认以便做有限重试。
13
+ * 不通过业务请求层鉴权,不要求账户就绪;任何失败都只返回 false。
14
+ * 重试复用完整 URL(同一 UUID/身份/发生时间),让 Worker 的 UUID 唯一索引去重。
15
+ */
16
+ export declare function createUsageReportingApi(getContext: () => UsageReportingContext): UsageReportingApi;
@@ -0,0 +1,2 @@
1
+ export declare function usageReportingText(value: string, maxLength: number, secrets: readonly string[]): string;
2
+ export declare function usageReportingData(value: unknown, secrets: readonly string[]): Record<string, unknown>;
@@ -0,0 +1,10 @@
1
+ /** 版本是 Canva 应用属性;不同应用共用 localhost 时也不能共享审核版本。 */
2
+ export declare const versionCacheKey: (appId: string) => string;
3
+ /** 测试额度同时隔离应用、产品和两套账户 ID;JSON 编码避免下划线拼接产生键冲突。 */
4
+ export declare function testCacheKey(kind: "test_info" | "test_free_cnt", appId: string, productName: string, userId?: string, uid?: string): string;
5
+ /** passport 沿用历史键名(只含 Canva userId),已缓存的票据升级后仍可复用。 */
6
+ export declare const passportCacheKey: (userId: string) => string;
7
+ /** 隐私模式/禁用存储不能阻断账户和消费流程。旧的全局 version/test_info/test_free_cnt 不再读取。 */
8
+ export declare function readCache(key: string): string | null;
9
+ export declare function writeCache(key: string, value: string): void;
10
+ export declare function removeCache(key: string): void;
@@ -0,0 +1,68 @@
1
+ import { ReportErrorParams, UsageApi } from '../api/types';
2
+ /** use() 的三个真实消费渠道;组合渠道会按月额度、积分的顺序各提交一次。 */
3
+ export type UseChannel = "free_cnt" | "monthly" | "monthly_and_free_cnt";
4
+ /** 已获得后端成功确认的数量;不包含本地乐观扣减,也不把超时推测成失败。 */
5
+ export interface ConfirmedUsage {
6
+ monthly: number;
7
+ freeCnt: number;
8
+ }
9
+ /** 可供应用诊断的消费错误,不包含 passport、JWT 或原始请求/响应正文。 */
10
+ export interface UseError {
11
+ code: string | number;
12
+ message: string;
13
+ status?: number;
14
+ }
15
+ export type UseSkipReason = "test_mode" | "in_review_test" | "free_unlimited" | "not_upload" | "account_changed";
16
+ type UseResultBase = {
17
+ confirmed: ConfirmedUsage;
18
+ };
19
+ /**
20
+ * use() 始终 resolve。charged=true 表示至少一项已确认扣费;全部成功还须判断 status。
21
+ * unknown 的 charged=null 表示可能已记账,禁止据此自动重试。
22
+ * partial 通过 confirmed 和 remaining 区分已成功部分与失败/未知/主动跳过的剩余部分。
23
+ */
24
+ export type UseResult = UseResultBase & ({
25
+ status: "charged";
26
+ charged: true;
27
+ channel: UseChannel;
28
+ } | {
29
+ status: "skipped";
30
+ charged: false;
31
+ reason: UseSkipReason;
32
+ } | {
33
+ status: "failed";
34
+ charged: false;
35
+ reason: "invalid_count" | "account_not_ready" | "request_failed";
36
+ error: UseError;
37
+ } | {
38
+ status: "unknown";
39
+ charged: null;
40
+ channel: UseChannel;
41
+ error: UseError;
42
+ } | {
43
+ status: "partial";
44
+ charged: true;
45
+ channel: "monthly_and_free_cnt";
46
+ remaining: "failed" | "unknown" | "skipped";
47
+ reason?: UseSkipReason;
48
+ error?: UseError;
49
+ });
50
+ export declare const skippedUsage: (reason: UseSkipReason) => UseResult;
51
+ /** 不信任任意异常文本;上报与公开结果均使用固定诊断,业务码/HTTP 状态单独保留。 */
52
+ export declare function usageFailure(error: unknown): UseError;
53
+ export declare function invalidUsageResult(): UseResult;
54
+ export declare function isValidUsageCount(cnt: number): boolean;
55
+ /**
56
+ * 这里只组织已计划的两种消费,不负责套餐判断和 React 状态。
57
+ * 每一步只发一次请求;月额度失败即停止,不继续扣积分。两次请求不是后端事务。
58
+ * report 是辅助通道,单次编排只上报一次,既不 await 也不允许拒绝泄漏到业务。
59
+ */
60
+ export declare function recordUsage(options: {
61
+ monthly: number;
62
+ freeCnt: number;
63
+ notUpload: boolean;
64
+ api: Pick<UsageApi, "reduceFreeCnt" | "addMonthlyUsage">;
65
+ isCurrent: () => boolean;
66
+ report: (params: ReportErrorParams) => unknown;
67
+ }): Promise<UseResult>;
68
+ export {};
@@ -1,14 +1,15 @@
1
1
  import { default as React } from 'react';
2
2
  import { AccountError } from './account';
3
- import { ChatApi, ContentExtractionApi, ErrorReportingApi, PredictionApi, TextModerationApi, UploadApi, UsageApi, VttApi } from '../api/types';
3
+ import { UseResult } from './consumption';
4
+ import { ChatApi, ContentExtractionApi, ErrorReportingApi, PredictionApi, TextModerationApi, TextToSpeechApi, UploadApi, UsageApi, UsageReportingApi, VttApi } from '../api/types';
4
5
  import { canUseError, CheckoutSessionOptions, TestMode, UserStatus } from './interface';
5
6
  /**
6
7
  * `useYiChongCanva()` 返回的客户端:账户状态、历史额度方法和后端同名 API 共用一个 Provider。
7
8
  *
8
9
  * `userStatus` 等字段随 React 渲染更新;后端 API 则在每次调用时读取 Provider 的最新身份引用。
9
- * 新的消费 API 会返回 Promise;历史 `use()` 是本地更新加异步上报,不能等待它确认服务器扣费。
10
+ * use() 返回不会 reject 的消费结果;同名消费 API 仍保留原始响应并以 ApiError 表达失败。
10
11
  */
11
- export interface YiChongCanvaContextType extends PredictionApi, TextModerationApi, ContentExtractionApi, ChatApi, VttApi, UsageApi, UploadApi, ErrorReportingApi {
12
+ export interface YiChongCanvaContextType extends PredictionApi, TextModerationApi, ContentExtractionApi, ChatApi, VttApi, TextToSpeechApi, UsageApi, UploadApi, ErrorReportingApi, UsageReportingApi {
12
13
  /** 当前账户快照;登录前为 `{}`。Canva 用户 ID 是 userId,系统用户 ID 是 profile.id。 */
13
14
  userStatus: UserStatus;
14
15
  /** 深度合并本地账户快照,并同步 API 使用的引用;不请求服务器,也不触发 onUpdateUserStatus。 */
@@ -25,10 +26,12 @@ export interface YiChongCanvaContextType extends PredictionApi, TextModerationAp
25
26
  isSubscribed: boolean;
26
27
  /**
27
28
  * 历史消费入口:默认消耗 1;订阅用户先用月额度再用积分,force=true 直接走积分分支。
28
- * 立即更新本地数值且不等待服务器成功;不会先执行 canUseLimit,也不会自动回滚。
29
- * notUpload 仅阻止积分扣费请求,当前订阅月用量分支仍会发送请求。需要明确响应时用同名消费 API。
29
+ * 本地余额乐观更新,不会先执行 canUseLimit 或自动回滚;消费请求无幂等保障,因此不自动重试。
30
+ * 同一账户的连续调用串行执行、使用最新余额;切换账户后旧队列不继续发新请求。
31
+ * notUpload 仅阻止积分扣费请求,订阅月用量仍会发送。结果明确区分全成功、跳过、失败、部分成功和未知。
32
+ * Promise 始终 resolve;旧应用可继续忽略返回值。partial 的 charged=true 仅表示部分已确认。
30
33
  */
31
- use: (cnt?: number, force?: boolean, notUpload?: boolean) => void;
34
+ use: (cnt?: number, force?: boolean, notUpload?: boolean) => Promise<UseResult>;
32
35
  /** 旧的纯本地判断:订阅用户在 force=false 时直接通过,不考虑月限额;force=true 只检查积分。 */
33
36
  canUse: (cnt?: number, force?: boolean) => boolean;
34
37
  /** 纯本地额度判断,默认检查 1 次;考虑月额度和积分。force=true 只查积分,免费无限仍直接通过。 */
@@ -73,6 +76,7 @@ export interface YiChongCanvaContextType extends PredictionApi, TextModerationAp
73
76
  /**
74
77
  * 默认 Context 仅用于兼容历史读取方式,不能替代真正的 Provider。
75
78
  * 缺少 Provider 时,历史账户方法返回空值或不执行操作;后端 API 明确拒绝 provider_missing。
79
+ * 行为统计是非阻塞辅助能力:缺少 Provider 的 reportUsage 只返回 false,不影响业务。
76
80
  * 由于这里提供了非空默认对象,useYiChongCanva 的空值保护本身不会在这种场景抛错。
77
81
  */
78
82
  export declare const YiChongCanvaContext: React.Context<YiChongCanvaContextType>;
@@ -4,3 +4,4 @@ export * from './interface';
4
4
  export * from './context';
5
5
  export * from './use_canva';
6
6
  export type { AccountError, AccountStage, AccountOperation } from './account';
7
+ export type { UseResult, UseChannel, UseError, UseSkipReason, ConfirmedUsage } from './consumption';
@@ -23,7 +23,7 @@ declare function getUserIds(token: string, appId: string, context: CommonRequest
23
23
  declare function handleUserLoginByCanvaId(userId: string, productName: string, context: CommonRequestContext, options?: AccountRequestOptions): Promise<Record<string, unknown>>;
24
24
  /**
25
25
  * 获取账户服务 passport,供 status 和消费请求的 X-Access-Ticket 使用。
26
- * 优先读取 localStorage 缓存;缓存键历史上只包含 Canva userId,不包含 productName。
26
+ * 优先读取本地缓存(存储被禁用时退回本页面内存);缓存键历史上只包含 Canva userId,不包含 productName。
27
27
  * 此处不主动检查过期;后续 status 缺少 profile 时,getUserProfile 会删除缓存再申请。
28
28
  *
29
29
  * imgkits 使用不带产品前缀的历史路径,其余产品使用产品前缀。
@@ -1,5 +1,6 @@
1
1
  import { default as React } from 'react';
2
2
  import { Mode, TestMode, UserStatus } from './interface';
3
+ import { UsageReportingConfig } from '../api/types';
3
4
  /**
4
5
  * 应用入口的账户与 API 配置。不同服务有独立根地址,修改其中一个不会自动改写其他服务地址。
5
6
  * productName 应使用后端登记的应用渠道名称,而不是界面中可随意修改的标题。
@@ -21,10 +22,18 @@ export interface YiChongCanvaProviderProps {
21
22
  contentBaseUrl?: string;
22
23
  /** 大模型 Chat 服务根地址,默认 https://ai.imgkits.com。 */
23
24
  chatBaseUrl?: string;
25
+ /** 文本转语音的异步创建/结果服务根地址,默认 https://ai.imgkits.com;与转录服务独立。 */
26
+ ttsBaseUrl?: string;
24
27
  /** 既有 Cloudflare R2 签名/分片接口根地址,默认 https://ai.imgkits.com。 */
25
28
  uploadBaseUrl?: string;
26
29
  /** 每次请求获取当前语言,用于 Accept-Language;缺省回退到浏览器语言,不要固定捕获过期语言。 */
27
30
  getLocale?: () => string;
31
+ /**
32
+ * 用户行为统计,默认开启并兼容旧 GET /api/report;与飞书错误上报独立。
33
+ * enabled=false 同时关闭公共与手动埋点;endpoint 可替换统计服务,appKey 可覆盖历史应用键。
34
+ * 自动补充当前身份、会话及应用发布号,登录前可发送;不读取或上报业务输入、结果正文。
35
+ */
36
+ usageReporting?: UsageReportingConfig;
28
37
  /** 默认 true,挂载后自动登录;false 时由 client.handleLogin/manualLogin 显式启动。 */
29
38
  autoLogin?: boolean;
30
39
  /** 初始模拟模式,默认 noTest;挂载 effect 会将开发环境设为 credits、其他环境设为 noTest。 */
@@ -58,4 +67,4 @@ export interface YiChongCanvaProviderProps {
58
67
  * // App 或其子组件内:const client = useYiChongCanva();
59
68
  * // 账号就绪后,直接调用 client.createSpecifyPrediction({ owner, name, input })。
60
69
  */
61
- export declare const YiChongCanvaProvider: ({ children, appId, productName, onUpdateUserStatus, baseUrl, apiBaseUrl, contentBaseUrl, chatBaseUrl, uploadBaseUrl, getLocale, autoLogin, testMode: _testMode, version, mode, retry, maxAvailablePoints, }: YiChongCanvaProviderProps) => React.JSX.Element;
70
+ export declare const YiChongCanvaProvider: ({ children, appId, productName, onUpdateUserStatus, baseUrl, apiBaseUrl, contentBaseUrl, chatBaseUrl, ttsBaseUrl, uploadBaseUrl, getLocale, usageReporting, autoLogin, testMode: _testMode, version, mode, retry, maxAvailablePoints, }: YiChongCanvaProviderProps) => React.JSX.Element;
@@ -1,11 +1,12 @@
1
1
  import { CommonRequestContext } from '../api/request';
2
+ import { ApiRequestOptions } from '../api/types';
2
3
  /** 远程配置中的应用数字版本,用于 Provider 判断审核/测试阶段,不是 npm 包的语义版本。 */
3
4
  export interface AppVersion {
4
- version: number;
5
+ version?: number;
5
6
  }
6
7
  /**
7
8
  * 从账户服务站点配置读取版本;Provider 使用 canva_<appId> 作为 key。
8
9
  * success=false 时运行时返回空对象,Provider 会对缺少数字 version 的情况按非测试处理。
9
- * 网络失败或配置 value 不是有效 JSON 时会 reject;此函数不重试、不缓存,也不归一化为 ApiError。
10
+ * 最长等待 10 秒,包含读取正文;支持 Provider 切换应用时取消。失败不重试、不缓存。
10
11
  */
11
- export declare function getAppVersion(key: string, context?: CommonRequestContext): Promise<AppVersion>;
12
+ export declare function getAppVersion(key: string, context?: CommonRequestContext, options?: ApiRequestOptions): Promise<AppVersion>;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "yichong-canva2",
3
- "version": "2.3.0",
3
+ "version": "2.5.0",
4
4
  "type": "module",
5
5
  "main": "./dist/index.js",
6
6
  "module": "./dist/index.js",