@tbox.cn/app-miniapp-container-alipay 0.2.3 → 0.2.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -69,6 +69,7 @@ H5 侧 `callJsapi(apiName, params, mode)`(平台 API)与 `callCapability(api
69
69
  | `navigateTo`(+`awaitEvent`) | my | 跳同小程序页,被打开页 eventChannel emit 后延迟回执(支付页场景) |
70
70
  | `startRecord` / `stopRecord` | **my** | 通过容器 `RecorderManager` 执行(mp3/16k,60s 自动停并缓存),stop 回 `{ audioBase64, format, duration }` |
71
71
  | `getLoginState` | **tbox** | 会员登录门禁(入会闭环):跳 `pages/mock-enrollment`(dev 脚手架,三按钮模拟真实 gate 语义),页 emit `login` 回执 `{loginStatus, message}` 延迟转发 H5;真实厂商壳接入后此分发可删 |
72
+ | `app.callCloudFunction` | **tbox** | 按 `appId + env` 缓存 `my.cloud.createCloudContext`,调用上下文的 `callFunction`,回传完整原生响应 |
72
73
  | 底层 API | my.call | 走 `my.call(apiName, params, cb)` |
73
74
 
74
75
  新增能力的双路径:
@@ -76,6 +77,30 @@ H5 侧 `callJsapi(apiName, params, mode)`(平台 API)与 `callCapability(api
76
77
  - **平台 API**(有 `my.xxx` 形态):H5 直接 `callJsapi('someApi', params)` 即可,壳子通用代理**零改动**;容器内部实现的 `startRecord/stopRecord` 由 `callJsapiForWebView` 转给 `RecorderManager`;其它需特殊后处理(如路径转 base64)时也在该处加分支。
77
78
  - **壳实现能力**(无 `my.*` 对应物):纯数据能力在 `pages/ai-agent/tbox-capabilities.ts` 注册一行 + H5 侧 `callCapability('xxx', params)`;应用自实现 apiName 约定 `app.*` 前缀(防与容器自带/平台词撞名)。未注册回 `CAPABILITY_NOT_REGISTERED`。
78
79
 
80
+ ### 云函数调用
81
+
82
+ `app.callCloudFunction` 入参:`name` 为必填非空字符串;`data` 为对象,缺省 `{}`;顶层 `appId` / `env` 为可选非空字符串,逐字段覆盖默认环境。默认配置在 `pages/ai-agent/cloud-function.ts` 的 `CLOUD_FN_CONFIG`:`appId = '2021004107679215'`、`env = 'env-00jy61udznyh'`。显式传空字符串、null 或错误类型返回 `INVALID_PARAMS`。
83
+
84
+ ```ts
85
+ import { callCapability } from '@tbox.cn/app-sdk-client';
86
+
87
+ // 使用默认环境
88
+ const response = await callCapability('app.callCloudFunction', {
89
+ name: 'queryUser',
90
+ data: { userId: '123' },
91
+ });
92
+
93
+ // 本次调用覆盖环境;也可只覆盖 appId 或 env
94
+ const customResponse = await callCapability('app.callCloudFunction', {
95
+ name: 'queryUser',
96
+ data: { userId: '123' },
97
+ appId: '你的应用 ID',
98
+ env: '你的云环境 ID',
99
+ });
100
+ ```
101
+
102
+ 缓存生命周期为小程序 JS 运行时:相同 `appId + env` 的不同云函数复用上下文,不同组合分别缓存;覆盖不修改默认配置。创建失败不缓存,后续调用可重试;云函数执行失败保留上下文。缺少云 API 或上下文 `callFunction` 时返回 `API_NOT_SUPPORTED`;原生调用抛错沿桥失败回执传递。响应不提取 `result`,H5 接收完整 `callFunction` 返回值,内容需可经 web-view 消息传输。
103
+
79
104
  ## 桥排障日志
80
105
 
81
106
  双侧结构化日志以 requestId 贯穿(H5 tag=`bridge`,壳 tag=`ai-agent`/`recorder`),**一个旋钮同时开两侧**:小程序 scheme 带 `?logLevel=debug`(壳 onLoad 读同一键 + H5 经 SDK 探测)。三步定位法:
@@ -105,6 +130,7 @@ miniapp-container-alipay/
105
130
  index.ts 桥主流程:门禁分流 → 执行 JSAPI/tbox 能力 → 回执;DEFAULT_H5_BASE/resolveH5Base 在这
106
131
  bridge.ts 消息解析/处置门禁/回执构建(协议工具,勿改协议常量)
107
132
  tbox-capabilities.ts tbox 能力注册表(纯数据 handler;应用自实现 app.* 在此注册)
133
+ cloud-function.ts 云函数能力(默认环境 + 单次覆盖 + 按环境复用上下文)
108
134
  log.ts 壳内 log-kit(镜像 SDK logger-core 纯函数子集,一致性测试锁死)
109
135
  jsapi-execution.ts invoke / call 模式决策
110
136
  recorder-handler.ts RecorderManager 录音封装(60s 自动停缓存状态机)
@@ -115,6 +141,7 @@ miniapp-container-alipay/
115
141
  tests/
116
142
  h5-base.test.ts h5Base 守卫 + URL 组装(H1–H6)
117
143
  bridge.test.ts 桥纯函数(B1–B10)+ 处置门禁 + tbox 注册表 + 与 SDK 的协议一致性
144
+ cloud-function.test.ts 云函数注册/参数/环境复用与隔离/失败重试
118
145
  log-kit.test.ts log-kit 脱敏/截断/级别 + 与 SDK logger-core 的镜像一致性
119
146
  mock-enrollment.test.ts 门禁回执纯函数 + dev-login/enroll URL 构造
120
147
  ```
@@ -122,3 +149,7 @@ miniapp-container-alipay/
122
149
  ## 取代关系
123
150
 
124
151
  本包取代早期独立发布的 `@tbox.cn/tbox-agent-app-alipay@1.0.0`(参考壳,不再维护)。
152
+
153
+ ### 云容器能力
154
+
155
+ `app.callContainer` 默认使用 `CLOUD_CONTAINER_ENV` 常量指定的云环境 `env-00jy61udznyh`;可传入顶层非空字符串 `env` 覆盖(去除首尾空格),无效值返回 `INVALID_PARAMS`。上下文按环境隔离缓存,同环境并发共用初始化,失败只清除对应环境缓存。`env` 仅用于初始化,不透传给底层请求。该能力将 H5 传入的 `path`、`method`、`header`、`data` 等请求参数交给云上下文 `callContainer`,返回原始响应。初始化失败可重试;调用异常原样抛出。容器不定义业务接口、校验买家身份、解释业务响应或提供业务 Mock。支付接口契约由 [AI 支付组件](../../modules/module-ai-payment/README.md) 维护。
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tbox.cn/app-miniapp-container-alipay",
3
- "version": "0.2.3",
3
+ "version": "0.2.5",
4
4
  "description": "tbox 支付宝小程序容器:web-view 承载智能体 H5 + JSAPI 桥代理(通用 my.xxx 透传 + 录音/媒体特殊处理)。tbox-app miniapp-container init 的展开源。",
5
5
  "license": "MIT",
6
6
  "publishConfig": {
@@ -24,8 +24,8 @@
24
24
  "@mini-types/alipay": "^3.0.14",
25
25
  "typescript": "5.9.3",
26
26
  "vitest": "4.1.10",
27
- "@tbox.cn/app-sdk-client": "0.21.2",
28
- "@tbox.cn/app-sdk-server": "0.24.1"
27
+ "@tbox.cn/app-sdk-client": "0.21.3",
28
+ "@tbox.cn/app-sdk-server": "0.25.0"
29
29
  },
30
30
  "scripts": {
31
31
  "dev": "minidev dev --typescript --less --hmr",
@@ -0,0 +1,32 @@
1
+ interface CloudContainerContext {
2
+ init(): Promise<unknown>;
3
+ callContainer(options: Record<string, unknown>): Promise<{ statusCode: number; data: unknown }>;
4
+ }
5
+ const CLOUD_CONTAINER_ENV = 'env-00jy61udznyh';
6
+ const CLOUD_CONTAINER_APP_ID = '2021004107679215';
7
+ const pendingContexts = new Map<string, Promise<CloudContainerContext>>();
8
+
9
+ async function getContext(env: string) {
10
+ let pendingContext = pendingContexts.get(env);
11
+ if (!pendingContext) {
12
+ pendingContext = (async () => {
13
+ const cloud = (my as unknown as { cloud?: { createCloudContext(config: { appId: string; env: string }): CloudContainerContext } }).cloud;
14
+ if (!cloud?.createCloudContext) throw new Error('当前支付宝版本不支持云容器');
15
+ const context = await cloud.createCloudContext({ appId: CLOUD_CONTAINER_APP_ID, env });
16
+ await context.init();
17
+ return context;
18
+ })().catch(error => { pendingContexts.delete(env); throw error; });
19
+ pendingContexts.set(env, pendingContext);
20
+ }
21
+ return pendingContext;
22
+ }
23
+
24
+ /** 云环境由容器管理,业务请求参数和响应解释由 H5 调用方负责。 */
25
+ export async function callCloudContainer(params: Record<string, unknown>) {
26
+ const { env = CLOUD_CONTAINER_ENV, ...options } = params;
27
+ if (typeof env !== 'string' || !env.trim()) {
28
+ throw { code: 'INVALID_PARAMS', errorMessage: 'env 必须是非空字符串' };
29
+ }
30
+ const context = await getContext(env.trim());
31
+ return context.callContainer(options);
32
+ }
@@ -0,0 +1,59 @@
1
+ /** 云上下文留在小程序端,H5 仅传入云函数参数并接收执行结果。 */
2
+ interface CloudConfig {
3
+ appId: string;
4
+ env: string;
5
+ }
6
+
7
+ interface CloudContext {
8
+ callFunction(options: { name: string; data: Record<string, unknown> }): Promise<unknown>;
9
+ }
10
+
11
+ interface CloudApi {
12
+ createCloudContext(config: CloudConfig): CloudContext;
13
+ }
14
+
15
+ const CLOUD_FN_CONFIG: Readonly<CloudConfig> = Object.freeze({
16
+ appId: '2021004107679215',
17
+ env: 'env-00jy61udznyh',
18
+ });
19
+
20
+ // 按完整环境键复用;不共享可变的“当前环境”,避免并发请求串环境。
21
+ const cloudContexts = new Map<string, CloudContext>();
22
+
23
+ function getStringParam(params: Record<string, unknown>, key: string, fallback?: string): string {
24
+ const value = params[key];
25
+ if (value === undefined && fallback !== undefined) return fallback;
26
+ if (typeof value !== 'string' || !value.trim()) {
27
+ throw { code: 'INVALID_PARAMS', errorMessage: `${key} 必须是非空字符串` };
28
+ }
29
+ return value.trim();
30
+ }
31
+
32
+ export async function callCloudFunction(params: Record<string, unknown>): Promise<unknown> {
33
+ const name = getStringParam(params, 'name');
34
+ const config = {
35
+ appId: getStringParam(params, 'appId', CLOUD_FN_CONFIG.appId),
36
+ env: getStringParam(params, 'env', CLOUD_FN_CONFIG.env),
37
+ };
38
+ const data = params.data === undefined ? {} : params.data;
39
+ if (Object.prototype.toString.call(data) !== '[object Object]') {
40
+ throw { code: 'INVALID_PARAMS', errorMessage: 'data 必须是对象' };
41
+ }
42
+
43
+ const contextKey = JSON.stringify([config.appId, config.env]);
44
+ let context = cloudContexts.get(contextKey);
45
+ if (!context) {
46
+ const cloud = (my as unknown as { cloud?: CloudApi }).cloud;
47
+ if (!cloud || typeof cloud.createCloudContext !== 'function') {
48
+ throw { code: 'API_NOT_SUPPORTED', errorMessage: 'my.cloud.createCloudContext 不存在' };
49
+ }
50
+ const created = cloud.createCloudContext(config);
51
+ if (!created || typeof created.callFunction !== 'function') {
52
+ throw { code: 'API_NOT_SUPPORTED', errorMessage: '云上下文 callFunction 不存在' };
53
+ }
54
+ cloudContexts.set(contextKey, created);
55
+ context = created;
56
+ }
57
+
58
+ return context.callFunction({ name, data: data as Record<string, unknown> });
59
+ }
@@ -259,8 +259,7 @@ Page<AiAgentPageData, AiAgentPageExtraThis>({
259
259
  return;
260
260
  }
261
261
 
262
- shellLogger.info(`my ${jsapiCall.apiName} req=${message.requestId}`);
263
- shellLogger.debug(`params=${detailForLog(jsapiCall.params)} req=${message.requestId}`);
262
+ shellLogger.info(`my ${jsapiCall.apiName} request req=${message.requestId}`, `params=${detailForLog(jsapiCall.params)}`);
264
263
 
265
264
  // navigateTo + awaitEvent:同小程序跳页并在被打开页 emit 后回执(延迟 receipt)
266
265
  if (isAwaitEventNavigateTo(jsapiCall.apiName, jsapiCall.params)) {
@@ -300,6 +299,7 @@ Page<AiAgentPageData, AiAgentPageExtraThis>({
300
299
 
301
300
  shellLogger.info(
302
301
  `my ${jsapiCall.apiName} ok ${Date.now() - startedAt}ms req=${message.requestId}`,
302
+ `result=${detailForLog(data)}`,
303
303
  );
304
304
  this.postMessageToWebView(
305
305
  buildMiniProgramReceipt({
@@ -315,6 +315,7 @@ Page<AiAgentPageData, AiAgentPageExtraThis>({
315
315
  const code = getErrorCode(error, 'REQUEST_FAILED');
316
316
  shellLogger.warn(
317
317
  `my ${jsapiCall.apiName} fail code=${code} ${Date.now() - startedAt}ms params=${detailForLog(jsapiCall.params)} req=${message.requestId}`,
318
+ `error=${detailForLog(error)}`,
318
319
  getErrorMessage(error, ''),
319
320
  );
320
321
  this.postMessageToWebView(
@@ -507,6 +508,7 @@ Page<AiAgentPageData, AiAgentPageExtraThis>({
507
508
  this.navigateToHandoffRequest = undefined;
508
509
  shellLogger.info(
509
510
  `my navigateTo ok ${Date.now() - startedAt}ms req=${message.requestId}`,
511
+ `result=${detailForLog(data)}`,
510
512
  );
511
513
  this.postMessageToWebView(
512
514
  buildMiniProgramReceipt({
@@ -8,9 +8,14 @@
8
8
  * 页面耦合能力(车牌键盘,需 setData/pending 簿记)不在此注册,由 index.ts 按名分发;
9
9
  * - 新增能力 = 此处注册一行 + H5 侧 callCapability('xxx', params)。
10
10
  */
11
+ import { callCloudContainer } from './cloud-container';
12
+ import { callCloudFunction } from './cloud-function';
13
+
11
14
  export type TboxCapabilityHandler = (params: Record<string, unknown>) => Promise<unknown>;
12
15
 
13
16
  const capabilities = new Map<string, TboxCapabilityHandler>();
17
+ capabilities.set('app.callCloudFunction', callCloudFunction);
18
+ capabilities.set('app.callContainer', callCloudContainer);
14
19
 
15
20
  /** 查注册表;未注册返回 undefined(调用方回执 CAPABILITY_NOT_REGISTERED) */
16
21
  export function getTboxCapability(apiName: string): TboxCapabilityHandler | undefined {
@@ -0,0 +1,64 @@
1
+ import { describe, expect, it, vi, afterEach } from 'vitest';
2
+ afterEach(() => { vi.unstubAllGlobals(); vi.resetModules(); });
3
+ describe('通用云容器桥', () => {
4
+ it('并发共用初始化,透传不同业务参数与原始响应', async () => {
5
+ const init = vi.fn(async () => {});
6
+ const response = { statusCode: 201, data: { value: 'result' } };
7
+ const callContainer = vi.fn(async () => response);
8
+ const createCloudContext = vi.fn(() => ({ init, callContainer }));
9
+ vi.stubGlobal('my', { cloud: { createCloudContext } });
10
+ const { callCloudContainer } = await import('../pages/ai-agent/cloud-container');
11
+ const first = { path: '/example/one', method: 'POST', header: { 'X-Alipay-Service': 'example' }, data: { value: 1 } };
12
+ const second = { path: '/example/two', method: 'GET' };
13
+ const results = await Promise.all([callCloudContainer(first), callCloudContainer(second)]);
14
+ expect(init).toHaveBeenCalledTimes(1);
15
+ expect(createCloudContext).toHaveBeenCalledWith({ appId: '2021004107679215', env: 'env-00jy61udznyh' });
16
+ expect(callContainer).toHaveBeenNthCalledWith(1, first);
17
+ expect(callContainer).toHaveBeenNthCalledWith(2, second);
18
+ expect(results).toEqual([response, response]);
19
+ });
20
+ it('初始化失败可重试,HTTP 状态由 H5 解释,调用异常原样抛出', async () => {
21
+ const init = vi.fn().mockRejectedValueOnce(new Error('初始化失败')).mockResolvedValue(undefined);
22
+ const callContainer = vi.fn().mockResolvedValueOnce({ statusCode: 400, data: {} }).mockRejectedValueOnce(new Error('网络失败'));
23
+ vi.stubGlobal('my', { cloud: { createCloudContext: () => ({ init, callContainer }) } });
24
+ const { callCloudContainer } = await import('../pages/ai-agent/cloud-container');
25
+ await expect(callCloudContainer({ path: '/example' })).rejects.toThrow('初始化失败');
26
+ await expect(callCloudContainer({ path: '/example' })).resolves.toEqual({ statusCode: 400, data: {} });
27
+ await expect(callCloudContainer({ path: '/example' })).rejects.toThrow('网络失败');
28
+ });
29
+ it('覆盖环境按 env 隔离缓存,同环境并发复用且不透传 env', async () => {
30
+ const contexts = new Map<string, { init: ReturnType<typeof vi.fn>; callContainer: ReturnType<typeof vi.fn> }>();
31
+ const createCloudContext = vi.fn(({ env }: { env: string }) => {
32
+ const context = { init: vi.fn(async () => {}), callContainer: vi.fn(async () => ({ statusCode: 200, data: env })) };
33
+ contexts.set(env, context);
34
+ return context;
35
+ });
36
+ vi.stubGlobal('my', { cloud: { createCloudContext } });
37
+ const { callCloudContainer } = await import('../pages/ai-agent/cloud-container');
38
+ const options = { path: '/example' };
39
+ const results = await Promise.all([
40
+ callCloudContainer(options),
41
+ callCloudContainer({ env: ' custom-env ', ...options }),
42
+ callCloudContainer({ env: 'custom-env', ...options }),
43
+ ]);
44
+ expect(createCloudContext).toHaveBeenCalledTimes(2);
45
+ expect(results.map(result => result.data)).toEqual(['env-00jy61udznyh', 'custom-env', 'custom-env']);
46
+ expect(contexts.get('custom-env')!.init).toHaveBeenCalledTimes(1);
47
+ expect(contexts.get('custom-env')!.callContainer).toHaveBeenNthCalledWith(1, options);
48
+ expect(contexts.get('custom-env')!.callContainer).toHaveBeenNthCalledWith(2, options);
49
+ });
50
+ it('拒绝无效环境,不初始化云上下文', async () => {
51
+ const createCloudContext = vi.fn();
52
+ vi.stubGlobal('my', { cloud: { createCloudContext } });
53
+ const { callCloudContainer } = await import('../pages/ai-agent/cloud-container');
54
+ for (const env of ['', ' ', null, 123]) {
55
+ await expect(callCloudContainer({ env, path: '/example' })).rejects.toMatchObject({ code: 'INVALID_PARAMS' });
56
+ }
57
+ expect(createCloudContext).not.toHaveBeenCalled();
58
+ });
59
+ it('只注册通用云容器能力', async () => {
60
+ const { getTboxCapability } = await import('../pages/ai-agent/tbox-capabilities');
61
+ expect(getTboxCapability('app.callContainer')).toBeTypeOf('function');
62
+ expect(getTboxCapability('app.createPaymentOrder')).toBeUndefined();
63
+ });
64
+ });
@@ -0,0 +1,108 @@
1
+ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
2
+
3
+ describe('app.callCloudFunction', () => {
4
+ beforeEach(() => vi.resetModules());
5
+ afterEach(() => vi.unstubAllGlobals());
6
+
7
+ async function setup() {
8
+ const contexts: Array<{ callFunction: ReturnType<typeof vi.fn> }> = [];
9
+ const createCloudContext = vi.fn((_config: { appId: string; env: string }) => {
10
+ const context = { callFunction: vi.fn().mockResolvedValue({ result: { ok: true } }) };
11
+ contexts.push(context);
12
+ return context;
13
+ });
14
+ vi.stubGlobal('my', { cloud: { createCloudContext } });
15
+ const { getTboxCapability } = await import('../pages/ai-agent/tbox-capabilities');
16
+ const handler = getTboxCapability('app.callCloudFunction')!;
17
+ expect(handler).toBeTypeOf('function');
18
+ return { handler, createCloudContext, contexts };
19
+ }
20
+
21
+ it('默认环境执行,保持云函数入参和原生响应', async () => {
22
+ const { handler, createCloudContext, contexts } = await setup();
23
+ const data = { userId: '123', nested: { values: [1, 2] } };
24
+ expect(await handler({ name: 'queryUser', data })).toEqual({ result: { ok: true } });
25
+ expect(createCloudContext).toHaveBeenCalledWith({ appId: '2021004107679215', env: 'env-00jy61udznyh' });
26
+ expect(contexts[0].callFunction).toHaveBeenCalledWith({ name: 'queryUser', data });
27
+ });
28
+
29
+ it('缺省 data 使用空对象;环境字段逐项覆盖默认值', async () => {
30
+ const { handler, createCloudContext, contexts } = await setup();
31
+ await handler({ name: 'queryUser', env: 'custom-env' });
32
+ await handler({ name: 'queryUser', appId: 'custom-app' });
33
+ expect(createCloudContext.mock.calls).toEqual([
34
+ [{ appId: '2021004107679215', env: 'custom-env' }],
35
+ [{ appId: 'custom-app', env: 'env-00jy61udznyh' }],
36
+ ]);
37
+ expect(contexts[0].callFunction).toHaveBeenCalledWith({ name: 'queryUser', data: {} });
38
+ });
39
+
40
+ it('同环境并发调用不同函数复用上下文,不同 appId/env 分别缓存', async () => {
41
+ const { handler, createCloudContext, contexts } = await setup();
42
+ await Promise.all([
43
+ handler({ name: 'first', appId: 'app-a', env: 'env-a' }),
44
+ handler({ name: 'second', appId: 'app-a', env: 'env-a' }),
45
+ handler({ name: 'third', appId: 'app-b', env: 'env-a' }),
46
+ handler({ name: 'fourth', appId: 'app-a', env: 'env-b' }),
47
+ ]);
48
+ await handler({ name: 'fifth', appId: 'app-a', env: 'env-a' });
49
+ expect(createCloudContext).toHaveBeenCalledTimes(3);
50
+ expect(contexts.map((context) => context.callFunction.mock.calls.map(([args]) => args.name)))
51
+ .toEqual([['first', 'second', 'fifth'], ['third'], ['fourth']]);
52
+ });
53
+
54
+ it('覆盖环境不改变后续请求的默认环境', async () => {
55
+ const { handler, createCloudContext } = await setup();
56
+ await handler({ name: 'queryUser', appId: 'custom-app', env: 'custom-env' });
57
+ await handler({ name: 'queryUser' });
58
+ await handler({ name: 'queryUser' });
59
+ expect(createCloudContext).toHaveBeenCalledTimes(2);
60
+ expect(createCloudContext).toHaveBeenLastCalledWith({ appId: '2021004107679215', env: 'env-00jy61udznyh' });
61
+ });
62
+
63
+ it.each([
64
+ {}, { name: '' }, { name: ' ' }, { name: 42 },
65
+ { name: 'queryUser', appId: '' }, { name: 'queryUser', env: null },
66
+ { name: 'queryUser', env: 42 }, { name: 'queryUser', data: null },
67
+ { name: 'queryUser', data: [] }, { name: 'queryUser', data: 'text' },
68
+ ])('非法参数不创建环境:%j', async (params) => {
69
+ const { handler, createCloudContext } = await setup();
70
+ await expect(handler(params)).rejects.toMatchObject({ code: 'INVALID_PARAMS' });
71
+ expect(createCloudContext).not.toHaveBeenCalled();
72
+ });
73
+
74
+ it.each([{}, { cloud: {} }, { cloud: { createCloudContext: 'invalid' } }])(
75
+ '缺少云 API 时明确失败:%j', async (myApi) => {
76
+ const { handler } = await setup();
77
+ vi.stubGlobal('my', myApi);
78
+ await expect(handler({ name: 'queryUser' })).rejects.toMatchObject({ code: 'API_NOT_SUPPORTED' });
79
+ },
80
+ );
81
+
82
+ it('创建失败不缓存,后续请求可重新创建', async () => {
83
+ const { handler, createCloudContext } = await setup();
84
+ const error = { code: 'CLOUD_INIT_FAILED', errorMessage: '初始化失败' };
85
+ createCloudContext.mockImplementationOnce(() => { throw error; });
86
+ await expect(handler({ name: 'queryUser' })).rejects.toBe(error);
87
+ await expect(handler({ name: 'queryUser' })).resolves.toEqual({ result: { ok: true } });
88
+ expect(createCloudContext).toHaveBeenCalledTimes(2);
89
+ });
90
+
91
+ it('无效上下文不缓存,后续请求可重新创建', async () => {
92
+ const { handler, createCloudContext } = await setup();
93
+ createCloudContext.mockReturnValueOnce({} as ReturnType<typeof createCloudContext>);
94
+ await expect(handler({ name: 'queryUser' })).rejects.toMatchObject({ code: 'API_NOT_SUPPORTED' });
95
+ await expect(handler({ name: 'queryUser' })).resolves.toEqual({ result: { ok: true } });
96
+ expect(createCloudContext).toHaveBeenCalledTimes(2);
97
+ });
98
+
99
+ it('云函数失败原样抛出,后续调用继续复用已创建的环境', async () => {
100
+ const { handler, createCloudContext, contexts } = await setup();
101
+ await handler({ name: 'queryUser' });
102
+ const error = { code: 'CLOUD_FUNCTION_FAILED', errorMessage: '云函数执行失败' };
103
+ contexts[0].callFunction.mockRejectedValueOnce(error);
104
+ await expect(handler({ name: 'queryUser' })).rejects.toBe(error);
105
+ await expect(handler({ name: 'queryUser' })).resolves.toEqual({ result: { ok: true } });
106
+ expect(createCloudContext).toHaveBeenCalledTimes(1);
107
+ });
108
+ });