@tbox.cn/app-module-activity-play 0.0.0-stage → 0.3.1

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 (40) hide show
  1. package/INTEGRATION.md +82 -0
  2. package/LICENSE +21 -0
  3. package/README.md +30 -2
  4. package/dist/chunk-CM4OEPC3.js +689 -0
  5. package/dist/chunk-HUBEOW44.js +98 -0
  6. package/dist/client/index.css +107 -0
  7. package/dist/client/index.d.ts +11 -0
  8. package/dist/client/index.js +6 -0
  9. package/dist/index.css +107 -0
  10. package/dist/index.d.ts +10 -0
  11. package/dist/index.js +46 -0
  12. package/dist/server/index.d.ts +309 -0
  13. package/dist/server/index.js +42 -0
  14. package/package.json +67 -3
  15. package/skills/activity-play/SKILL.md +55 -0
  16. package/src/client/cards/activity-play/ActivityPlayCard.tsx +77 -0
  17. package/src/client/cards/activity-play/index.ts +1 -0
  18. package/src/client/cards/view.ts +42 -0
  19. package/src/client/index.ts +22 -0
  20. package/src/client/styles/activity-play.css +136 -0
  21. package/src/index.ts +6 -0
  22. package/src/server/cards/activity-play/meta.ts +26 -0
  23. package/src/server/cards/activity-play/samples.ts +116 -0
  24. package/src/server/cards/index.ts +7 -0
  25. package/src/server/errors.ts +101 -0
  26. package/src/server/index.ts +72 -0
  27. package/src/server/ports.ts +50 -0
  28. package/src/server/query.ts +98 -0
  29. package/src/server/routes.ts +371 -0
  30. package/src/server/tools.ts +187 -0
  31. package/tbox.module.json +62 -0
  32. package/tests/cards-capture.test.ts +110 -0
  33. package/tests/entry.test.ts +458 -0
  34. package/tests/ports.test.ts +83 -0
  35. package/tests/routes.test.ts +271 -0
  36. package/tests/samples.test.ts +53 -0
  37. package/tests/smoke.test.ts +27 -0
  38. package/tests/tools.test.ts +251 -0
  39. package/tsconfig.json +8 -0
  40. package/tsup.config.ts +27 -0
@@ -0,0 +1,271 @@
1
+ /**
2
+ * 活动玩法 HTTP 接口行为测试(supertest 装配真实 Router + 会话上下文中间件)。
3
+ * 覆盖风险≡验收点:scope 冲突/补齐、参数合法性、错误域区分(503/502/404)、
4
+ * 空目录非错误、错误信封形状、客户端身份字段不可覆盖查询主体。
5
+ */
6
+ import { describe, expect, it, vi, beforeEach } from 'vitest';
7
+ import express from 'express';
8
+ import type { Express, Request, Response, NextFunction } from 'express';
9
+ import request from 'supertest';
10
+ import type { ServerContext } from '@tbox.cn/app-agent-sdk-server';
11
+ import type { RequestContext } from '@tbox.cn/app-contracts';
12
+ import {
13
+ ACTIVITY_PLAY_QUERY_SERVICE,
14
+ withMallScopeFromQuery,
15
+ type ActivityPlayQueryContext,
16
+ type ActivityPlayQueryPort,
17
+ } from '@tbox.cn/app-contracts-mall';
18
+ import { createActivityPlayRouter } from '../src/server/routes';
19
+
20
+ /** 会话基础上下文(登录态 guest——等同浏览器轴 guest 登录产物) */
21
+ const baseReqCtx = (): RequestContext => ({
22
+ identity: { userId: 'guest_abc', source: 'guest' },
23
+ });
24
+
25
+ interface PortCall {
26
+ q: ActivityPlayQueryContext;
27
+ input?: { keyword?: string; limit?: number };
28
+ activityRef?: string;
29
+ }
30
+
31
+ /** 可观测 Port 替身(记录调用 + 可配置返回/抛错) */
32
+ function makePort(overrides: Partial<ActivityPlayQueryPort> = {}) {
33
+ const calls: PortCall[] = [];
34
+ const port: ActivityPlayQueryPort = {
35
+ async listActivities(q, input) {
36
+ calls.push({ q, input });
37
+ return { items: [] };
38
+ },
39
+ async getActivity(q, activityRef) {
40
+ calls.push({ q, activityRef });
41
+ return null;
42
+ },
43
+ ...overrides,
44
+ };
45
+ return { port, calls };
46
+ }
47
+
48
+ interface Harness {
49
+ app: Express;
50
+ calls: PortCall[];
51
+ resolveService: ReturnType<typeof vi.fn>;
52
+ }
53
+
54
+ /** 装配被测 App:auth 形中间件写入 reqCtx → 挂模块 Router(stub ctx)。
55
+ * 缺省 port = 可观测替身(空目录);自定义 port 时 calls 不记录(相应用例不校验调用面)。 */
56
+ function makeApp(opts: {
57
+ reqCtx: RequestContext | undefined;
58
+ port?: ActivityPlayQueryPort;
59
+ resolveError?: unknown;
60
+ }): Harness {
61
+ const { port: defaultPort, calls } = makePort();
62
+ const resolveService = vi.fn(async () => {
63
+ if (opts.resolveError) throw opts.resolveError;
64
+ return opts.port ?? defaultPort;
65
+ });
66
+ const ctxStub = {
67
+ integrations: { resolveService },
68
+ logger: { warn: vi.fn() },
69
+ } as unknown as ServerContext;
70
+ const app = express();
71
+ app.use((req: Request, _res: Response, next: NextFunction) => {
72
+ if (opts.reqCtx) (req as unknown as Record<string, unknown>)['tboxAuthContext'] = opts.reqCtx;
73
+ next();
74
+ });
75
+ app.use(createActivityPlayRouter(ctxStub));
76
+ return { app, calls, resolveService };
77
+ }
78
+
79
+ const ITEM = {
80
+ activityRef: 'demo:wheel',
81
+ title: '幸运转盘',
82
+ status: 'active',
83
+ loginRequired: false,
84
+ } as const;
85
+
86
+ describe('GET /api/m/activity-play/activities(列表)', () => {
87
+ it('正常查询:query mallId 注入,keyword 透传,limit 缺省 20;信封 {"data":{"items":[]}}', async () => {
88
+ const h = makeApp({ reqCtx: baseReqCtx() });
89
+ const res = await request(h.app).get('/activities?mallId=mall-a');
90
+ expect(res.status).toBe(200);
91
+ expect(res.body).toEqual({ data: { items: [] } });
92
+ expect(h.calls).toHaveLength(1);
93
+ expect(h.calls[0]?.input).toEqual({ limit: 20 });
94
+ expect(h.calls[0]?.q.scope.mallId).toBe('mall-a');
95
+ expect(h.resolveService).toHaveBeenCalledWith(
96
+ expect.objectContaining({ service: ACTIVITY_PLAY_QUERY_SERVICE, scope: { mallId: 'mall-a' } }),
97
+ );
98
+ });
99
+
100
+ it('空目录(配置完整零活动)= 200 空 items,绝不当错误或回退演示数据', async () => {
101
+ const h = makeApp({ reqCtx: baseReqCtx() });
102
+ const res = await request(h.app).get('/activities?mallId=mall-a');
103
+ expect(res.status).toBe(200);
104
+ expect(res.body.data.items).toEqual([]);
105
+ });
106
+
107
+ it('验收返修:普通字符串字面量是合法输入(keyword/mallId 值 = "invalid" 不得误判参数错误)', async () => {
108
+ const h = makeApp({ reqCtx: baseReqCtx() });
109
+ // keyword=invalid:只是匹配不到任何活动(大小写归 provider,路由不掺和)
110
+ expect((await request(h.app).get('/activities?mallId=mall-a&keyword=invalid')).status).toBe(200);
111
+ expect(h.calls.at(-1)?.input?.keyword).toBe('invalid');
112
+ expect(h.calls.at(-1)?.q.scope.mallId).toBe('mall-a');
113
+ expect((await request(h.app).get('/activities?mallId=mall-a&keyword=INVALID')).status).toBe(200);
114
+ // mallId=invalid:形状合法,路由放行(实例白名单裁决归 registry;stub 恒出品)
115
+ expect((await request(h.app).get('/activities?mallId=invalid')).status).toBe(200);
116
+ expect(h.calls.at(-1)?.q.scope.mallId).toBe('invalid');
117
+ });
118
+
119
+ it('keyword/mallId 数组多值仍显式 400 INVALID_REQUEST(非哨兵语义变化不影响)', async () => {
120
+ const h = makeApp({ reqCtx: baseReqCtx() });
121
+ expect((await request(h.app).get('/activities?mallId=mall-a&keyword=a&keyword=b')).status).toBe(400);
122
+ expect((await request(h.app).get('/activities?mallId=a&mallId=b')).status).toBe(400);
123
+ });
124
+
125
+ it('keyword/limit 契约:keyword 命中透传;limit=1 与 50 合法、0/51/非数字 → 400 INVALID_REQUEST', async () => {
126
+ const h = makeApp({ reqCtx: baseReqCtx() });
127
+ expect((await request(h.app).get('/activities?mallId=mall-a&keyword=%E8%BD%AC%E7%9B%98&limit=3')).status).toBe(200);
128
+ expect(h.calls[0]?.input).toEqual({ keyword: '转盘', limit: 3 });
129
+
130
+ expect((await request(h.app).get('/activities?mallId=mall-a&limit=1')).status).toBe(200);
131
+ expect((await request(h.app).get('/activities?mallId=mall-a&limit=50')).status).toBe(200);
132
+ // 评审返修:limit 空串/纯空白 = 非法值 400(不静默当缺省——任务 01 语义回归)
133
+ expect((await request(h.app).get('/activities?mallId=mall-a&limit=')).status).toBe(400);
134
+ expect((await request(h.app).get('/activities?mallId=mall-a&limit=%20')).status).toBe(400);
135
+ for (const bad of ['0', '51', 'abc', '-1', '20.5', '20.0', '2e1']) {
136
+ const res = await request(h.app).get(`/activities?mallId=mall-a&limit=${bad}`);
137
+ expect(res.status, `limit=${bad}`).toBe(400);
138
+ expect(res.body.error.code).toBe('INVALID_REQUEST');
139
+ }
140
+ });
141
+
142
+ it('商圈缺口:无 query mallId 且上下文无绑定 → 400 SCOPE_REQUIRED;畸形 mallId → 400', async () => {
143
+ const h = makeApp({ reqCtx: baseReqCtx() });
144
+ const res = await request(h.app).get('/activities');
145
+ expect(res.status).toBe(400);
146
+ expect(res.body.error.code).toBe('SCOPE_REQUIRED');
147
+
148
+ const res2 = await request(h.app).get('/activities?mallId=bad%20mall%24');
149
+ expect(res2.status).toBe(400);
150
+ expect(res2.body.error.code).toBe('INVALID_REQUEST');
151
+ });
152
+
153
+ it('商圈冲突:上下文已绑定 mall-a,query mall-b → 403 SCOPE_MISMATCH;一致则放行', async () => {
154
+ const bound = withMallScopeFromQuery(baseReqCtx(), { mallId: 'mall-a' });
155
+ const h = makeApp({ reqCtx: bound });
156
+ const res = await request(h.app).get('/activities?mallId=mall-b');
157
+ expect(res.status).toBe(403);
158
+ expect(res.body.error.code).toBe('SCOPE_MISMATCH');
159
+
160
+ const ok = await request(h.app).get('/activities?mallId=mall-a');
161
+ expect(ok.status).toBe(200);
162
+ expect(h.calls[0]?.q.scope.mallId).toBe('mall-a');
163
+ });
164
+
165
+ it('仅有绑定(无 query)→ 用绑定商圈解析;不要求显式 mallId 透传', async () => {
166
+ const bound = withMallScopeFromQuery(baseReqCtx(), { mallId: 'mall-a' });
167
+ const h = makeApp({ reqCtx: bound });
168
+ const res = await request(h.app).get('/activities');
169
+ expect(res.status).toBe(200);
170
+ expect(h.calls[0]?.q.scope.mallId).toBe('mall-a');
171
+ });
172
+
173
+ it('客户端身份字段不可覆盖查询主体:userId query 只是被忽略的未知参数', async () => {
174
+ const bound = withMallScopeFromQuery(baseReqCtx(), { mallId: 'mall-a' });
175
+ const h = makeApp({ reqCtx: bound });
176
+ await request(h.app).get('/activities?mallId=mall-a&userId=attacker&openid=x&memberId=1');
177
+ expect(h.calls[0]?.q.subjectId).toBe('guest_abc');
178
+ expect(h.calls[0]?.q.requestContext.identity.userId).toBe('guest_abc');
179
+ });
180
+
181
+ it('匿名身份:subjectId 缺席(目录查询不因匿名拒绝——登录要求归入口任务)', async () => {
182
+ const anonymous: RequestContext = { identity: { userId: 'anon_x', source: 'anonymous' } };
183
+ const h = makeApp({ reqCtx: anonymous });
184
+ const res = await request(h.app).get('/activities?mallId=mall-a');
185
+ expect(res.status).toBe(200);
186
+ expect(h.calls[0]?.q.subjectId).toBeUndefined();
187
+ });
188
+
189
+ it('供给配置缺席族 → 503 NOT_CONFIGURED(三个预期缺席码逐一)', async () => {
190
+ for (const code of ['PROVIDER_SERVICE_NOT_CONFIGURED', 'PROVIDER_INSTANCE_NOT_FOUND', 'PROVIDER_INSTANCE_DISABLED']) {
191
+ const h = makeApp({ reqCtx: baseReqCtx(), resolveError: Object.assign(new Error('boom'), { code }) });
192
+ const res = await request(h.app).get('/activities?mallId=mall-a');
193
+ expect(res.status, code).toBe(503);
194
+ expect(res.body.error.code).toBe('NOT_CONFIGURED');
195
+ }
196
+ });
197
+
198
+ it('供给绑定解析/未实施族 → 503 NOT_CONFIGURED;装配缺口显性可区分', async () => {
199
+ for (const code of ['PROVIDER_BINDING_UNRESOLVED', 'PROVIDER_NOT_IMPLEMENTED', 'PROVIDER_NOT_FOUND']) {
200
+ const h = makeApp({ reqCtx: baseReqCtx(), resolveError: Object.assign(new Error('boom'), { code }) });
201
+ const res = await request(h.app).get('/activities?mallId=mall-a');
202
+ expect(res.status, code).toBe(503);
203
+ expect(res.body.error.code).toBe('NOT_CONFIGURED');
204
+ }
205
+ });
206
+
207
+ it('供给配置非法/执行异常 → 502 PROVIDER_ERROR,且不透传原始 message', async () => {
208
+ const h = makeApp({
209
+ reqCtx: baseReqCtx(),
210
+ resolveError: new Error('原始敏感细节: activities[2].title missing'),
211
+ });
212
+ const res = await request(h.app).get('/activities?mallId=mall-a');
213
+ expect(res.status).toBe(502);
214
+ expect(res.body.error.code).toBe('PROVIDER_ERROR');
215
+ expect(JSON.stringify(res.body)).not.toContain('敏感细节');
216
+ });
217
+ });
218
+
219
+ describe('GET /api/m/activity-play/activities/:activityRef(详情)', () => {
220
+ it('评审返修回归:数字/布尔形态合法字面量引用 200(原始字串——HTTP/工具同参同果)', async () => {
221
+ const refs = ['1.2', 'true'];
222
+ const { port } = makePort({ async getActivity(_q, ref) { return { ...ITEM, activityRef: ref }; } });
223
+ const h = makeApp({ reqCtx: baseReqCtx(), port });
224
+ for (const ref of refs) {
225
+ const res = await request(h.app).get(`/activities/${ref}?mallId=mall-a`);
226
+ expect(res.status, ref).toBe(200);
227
+ expect(res.body.data.activityRef).toBe(ref);
228
+ }
229
+ });
230
+
231
+ it('命中:返回 {"data":活动对象};activityRef 原样透传(含冒号)', async () => {
232
+ const { port } = makePort({ async getActivity() { return { ...ITEM }; } });
233
+ const h = makeApp({ reqCtx: baseReqCtx(), port });
234
+ const res = await request(h.app).get('/activities/demo:wheel?mallId=mall-a');
235
+ expect(res.status).toBe(200);
236
+ expect(res.body).toEqual({ data: ITEM });
237
+ });
238
+
239
+ it('未知引用 → 404 ACTIVITY_NOT_FOUND(独立于供给缺席的 503)', async () => {
240
+ const h = makeApp({ reqCtx: baseReqCtx() });
241
+ const res = await request(h.app).get('/activities/demo:none?mallId=mall-a');
242
+ expect(res.status).toBe(404);
243
+ expect(res.body.error.code).toBe('ACTIVITY_NOT_FOUND');
244
+ });
245
+
246
+ it('畸形 activityRef → 400 INVALID_REQUEST;商圈规则与列表一致', async () => {
247
+ const h = makeApp({ reqCtx: baseReqCtx() });
248
+ expect((await request(h.app).get('/activities/%20?mallId=mall-a')).status).toBe(400);
249
+ expect((await request(h.app).get('/activities/demo:wheel')).status).toBe(400);
250
+ expect((await request(h.app).get('/activities/demo:wheel?mallId=')).status).toBe(400);
251
+ });
252
+
253
+ beforeEach(() => { vi.clearAllMocks(); });
254
+ });
255
+
256
+ describe('错误信封与调用面', () => {
257
+ it('统一错误信封 {"error":{"code","message"}}(三面抽查)', async () => {
258
+ const h = makeApp({ reqCtx: baseReqCtx() });
259
+ const bad = await request(h.app).get('/activities');
260
+ expect(Object.keys(bad.body)).toEqual(['error']);
261
+ expect(Object.keys(bad.body.error).sort()).toEqual(['code', 'message']);
262
+ expect(typeof bad.body.error.message).toBe('string');
263
+ });
264
+
265
+ it('无鉴权装配旁路(无可信上下文)→ 401 LOGIN_REQUIRED 显性拒绝', async () => {
266
+ const h = makeApp({ reqCtx: undefined });
267
+ const res = await request(h.app).get('/activities?mallId=mall-a');
268
+ expect(res.status).toBe(401);
269
+ expect(res.body.error.code).toBe('LOGIN_REQUIRED');
270
+ });
271
+ });
@@ -0,0 +1,53 @@
1
+ /**
2
+ * activity-play 卡样本双断言(样本即契约,对齐 promotion/member 模式):
3
+ * 全样本(含 sampleData 初始态)dataSchema.safeParse 通过 + findSampleShapeViolations
4
+ * 无越界键;覆盖维度(列表/详情/空态/四种状态)结构性在场——防钟样例集体漂移成
5
+ * "都是列表"之类(T02-05 验收面的模块侧自锁)。
6
+ */
7
+ import { describe, expect, it } from 'vitest';
8
+ import { findSampleShapeViolations } from '@tbox.cn/app-agent-sdk-server';
9
+ import { activityPlayCardDataSchema } from '@tbox.cn/app-contracts-mall';
10
+ import meta from '../src/server/cards/activity-play/meta';
11
+
12
+ const sampledModes = new Set(((meta.samples ?? []).map((s) => (s.data as { mode: string }).mode)));
13
+ const sampledStatuses = new Set(
14
+ (meta.samples ?? []).flatMap((s) => (s.data as { items: { status: string }[] }).items.map((i) => i.status)),
15
+ );
16
+
17
+ describe('activity-play 样本即契约(T02-05)', () => {
18
+ it('sampleData 与全附加样本过 dataSchema + shape 无越界键', () => {
19
+ expect(activityPlayCardDataSchema.safeParse(meta.sampleData).success).toBe(true);
20
+ expect(findSampleShapeViolations(meta).violations).toEqual([]);
21
+ for (const s of meta.samples ?? []) {
22
+ expect(activityPlayCardDataSchema.safeParse(s.data).success, `${meta.cardType}/${s.label}`).toBe(true);
23
+ }
24
+ });
25
+
26
+ it('覆盖维度在场:list(含空态)+ detail;四种状态全覆盖', () => {
27
+ expect(sampledModes.has('list')).toBe(true);
28
+ expect(sampledModes.has('detail')).toBe(true);
29
+ const listEmpty = (meta.samples ?? []).some(
30
+ (s) => (s.data as { mode: string; items: unknown[] }).mode === 'list'
31
+ && (s.data as { items: unknown[] }).items.length === 0,
32
+ );
33
+ expect(listEmpty).toBe(true);
34
+ for (const status of ['not_started', 'active', 'ended', 'disabled']) {
35
+ expect(sampledStatuses.has(status), `样本缺状态 ${status}`).toBe(true);
36
+ }
37
+ });
38
+
39
+ it('样本不含 B 端 enabled 配置字段与未知键(卡 data 面 = 契约 strict 面)', () => {
40
+ for (const s of [ { label: 'sampleData', data: meta.sampleData }, ...(meta.samples ?? []) ]) {
41
+ const items = (s.data as { items: Record<string, unknown>[] }).items;
42
+ for (const item of items) {
43
+ expect(item['enabled'], `${s.label}`).toBeUndefined();
44
+ }
45
+ }
46
+ });
47
+
48
+ it('样本 mallId 恒 demo 商圈(卡片 mallId 语义 = 执行上下文投影位)', () => {
49
+ for (const s of meta.samples ?? []) {
50
+ expect((s.data as { mallId: string }).mallId).toBe('mall-demo');
51
+ }
52
+ });
53
+ });
@@ -0,0 +1,27 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import { serverModule } from '../src/server/index';
3
+ import { clientModule } from '../src/client/index';
4
+
5
+ describe('module-activity-play 模块形态(铁律冒烟)', () => {
6
+ it('双端描述对象在场且自洽(satisfies ServerModule/ClientModule 编译期锁)', () => {
7
+ expect(serverModule).toBeTruthy();
8
+ expect(clientModule).toBeTruthy();
9
+ // 2026-11-16 起含授权占位 renderer(单卡型与 server 侧对齐——铁律 cards key = meta.cardType)
10
+ expect(Object.keys(clientModule.cards)).toEqual(['activity-play']);
11
+ });
12
+
13
+ it('cards key 约定 = meta.cardType(key 恒等于 meta.cardType——铁律位)', () => {
14
+ for (const [key, meta] of Object.entries(serverModule.cards)) {
15
+ expect(key).toBe(meta.cardType);
16
+ }
17
+ });
18
+
19
+ it('出卡卡型唯一(activity-play——mode 承载列表/详情,不拆多卡型)', () => {
20
+ expect(Object.keys(serverModule.cards)).toEqual(['activity-play']);
21
+ });
22
+
23
+ it('本地技能声明接线(skills map 键 = skill 名,前置 name=activity-play)', () => {
24
+ expect(Object.keys(serverModule.skills)).toContain('activity-play');
25
+ expect(serverModule.skills['activity-play']?.name).toBe('activity-play');
26
+ });
27
+ });
@@ -0,0 +1,251 @@
1
+ /**
2
+ * 活动玩法只读工具行为测试(直接 execute 真实工具实例 + stub integrations ctx)。
3
+ * 覆盖风险≡验收点:
4
+ * - 输入契约:无 mallId/userId 等 scope 字段;limit 归一(缺省/非法显性拒绝);
5
+ * keyword=invalid 是普通关键词(不哨兵化);
6
+ * - 出卡契约:非空 → cards 候选(cardType/activity-play + data 过卡契约 + note ≤120);
7
+ * 空结果/失败路径无 cards 键;失败 fact 含可辨识 errorCode,原始异常不透出;
8
+ * - 上下文:mallId/身份恒取 execCtx(跨用户/跨商圈连续调用各自解析——stub 逐次断言);
9
+ * - 复用:与 errors.ts 分类单源(三个缺席码 → NOT_CONFIGURED;供给异常 → PROVIDER_ERROR)。
10
+ */
11
+ import { describe, expect, it, vi } from 'vitest';
12
+ import { createToolExecContext } from '@tbox.cn/app-agent-sdk-server';
13
+ import type { RequestContext } from '@tbox.cn/app-contracts';
14
+ import { activityPlayActivitySchema, activityPlayCardDataSchema } from '@tbox.cn/app-contracts-mall';
15
+ import { createActivityPlayTools, ACTIVITY_PLAY_CARD_TYPE } from '../src/server/tools';
16
+ import { resolveActivityPlayQueryPort } from '../src/server/ports';
17
+ import type { ServerContext } from '@tbox.cn/app-agent-sdk-server';
18
+
19
+ vi.mock('../src/server/ports', () => ({
20
+ resolveActivityPlayQueryPort: vi.fn(),
21
+ }));
22
+
23
+ const resolvePortMock = vi.mocked(resolveActivityPlayQueryPort);
24
+
25
+ /** reqCtx:登录态 guest + 绑定商圈(工具路径无 query 注入——scope 恒取上下文绑定) */
26
+ const reqCtxOf = (mallId: string, userId = 'guest_1'): RequestContext => ({
27
+ identity: { userId, source: 'guest' },
28
+ attributes: { mall: { mallId } },
29
+ });
30
+
31
+ const ITEM = {
32
+ activityRef: 'demo:wheel',
33
+ title: '幸运大转盘',
34
+ description: '进入活动页面查看参与规则',
35
+ status: 'active' as const,
36
+ loginRequired: false,
37
+ };
38
+ const ITEM_B = {
39
+ activityRef: 'demo:checkin',
40
+ title: '签到有礼',
41
+ startsAt: '2027-01-01T00:00:00+08:00',
42
+ status: 'not_started' as const,
43
+ loginRequired: true,
44
+ };
45
+
46
+ function makeTools(port: unknown) {
47
+ resolvePortMock.mockImplementation(async () => port as never);
48
+ const ctx = {} as ServerContext;
49
+ return createActivityPlayTools({ getCtx: () => ctx });
50
+ }
51
+
52
+ /** 真实端口行为替身(provenance: supplier 语义下沉到 stub——工具层只编排) */
53
+ const listPort = (items: readonly unknown[]) => ({
54
+ listActivities: vi.fn(async (q: unknown, input: { keyword?: string; limit?: number }) => {
55
+ lastListCall = { q, input };
56
+ return { items: (items as never[]) };
57
+ }),
58
+ getActivity: vi.fn(async (_q: unknown, ref: string) => (items as never[]).find((i: { activityRef?: string }) => i.activityRef === ref) ?? null),
59
+ });
60
+ let lastListCall: { q: unknown; input: { keyword?: string; limit?: number } } | undefined;
61
+
62
+ describe('listActivityPlays', () => {
63
+ it('非空目录:答话事实 + 一张 mode=list 卡候选;data 过卡契约;note ≤120', async () => {
64
+ const tools = makeTools(listPort([ITEM, ITEM_B]));
65
+ const result = await tools.listActivityPlays.execute!({}, createToolExecContext(reqCtxOf('mall-a')) as never) as Record<string, unknown>;
66
+ expect(result['found']).toBe(true);
67
+ expect(result['count']).toBe(2);
68
+ expect((result['items'] as Array<{ activityRef: string }>).map((i) => i.activityRef)).toEqual(['demo:wheel', 'demo:checkin']);
69
+ const cards = result['cards'] as Array<{ cardType: string; data: unknown; note: string }>;
70
+ expect(cards).toHaveLength(1);
71
+ expect(cards[0]?.cardType).toBe(ACTIVITY_PLAY_CARD_TYPE);
72
+ activityPlayCardDataSchema.parse(cards[0]?.data);
73
+ for (const item of (cards[0]?.data as { items: unknown[] }).items) {
74
+ expect(activityPlayActivitySchema.safeParse(item).success).toBe(true);
75
+ }
76
+ expect(cards[0]?.note.length).toBeLessThanOrEqual(120);
77
+ expect(cards[0]?.note).toContain('幸运大转盘');
78
+ // mallId 取自可信上下文(result facts/native data 双处一致)
79
+ expect((result['mallId'] as string)).toBe('mall-a');
80
+ expect((cards[0]?.data as { mallId: string }).mallId).toBe('mall-a');
81
+ // 透传供给入参:缺省 limit 20;keyword 缺席
82
+ expect(lastListCall?.input).toEqual({ limit: 20 });
83
+ expect((lastListCall?.q as { scope: { mallId: string } }).scope.mallId).toBe('mall-a');
84
+ });
85
+
86
+ it('keyword/limit 处理:透传;缺省 limit 20;非法整数字串 = 显性失败 fact;小数/负数字串 = 框架输入校验拒绝', async () => {
87
+ const tools = makeTools(listPort([ITEM]));
88
+ const ok = await tools.listActivityPlays.execute!({ keyword: ' invalid ', limit: '3' }, createToolExecContext(reqCtxOf('mall-a')) as never) as Record<string, unknown>;
89
+ expect(ok['found']).toBe(true);
90
+ expect(lastListCall?.input).toEqual({ keyword: 'invalid', limit: 3 }); // trim;'invalid' 是普通关键词
91
+
92
+ // 空串/纯空白 = 非法值显性拒绝(评审返修:不静默当缺省——"未传"才走缺省)
93
+ for (const blank of ['', ' ']) {
94
+ const result = await tools.listActivityPlays.execute!({ limit: blank }, createToolExecContext(reqCtxOf('mall-a')) as never) as Record<string, unknown>;
95
+ expect(result['found'], `limit=${JSON.stringify(blank)}`).toBe(false);
96
+ expect(result['errorCode']).toBe('INVALID_REQUEST');
97
+ expect(result['cards']).toBeUndefined();
98
+ }
99
+ // 评审点名用例:'20.0'/'2e1' 是非规范数字格式——与 HTTP 同拒(JSON 转换移除后不再
100
+ // 折叠成功);'20.5'/'-1' 同由归一拒绝
101
+ for (const bad of ['20.0', '2e1', '1e3', '20.5', '-1']) {
102
+ const result = await tools.listActivityPlays.execute!({ limit: bad }, createToolExecContext(reqCtxOf('mall-a')) as never) as Record<string, unknown>;
103
+ expect(result['found'], `limit=${bad}`).toBe(false);
104
+ expect(result['errorCode']).toBe('INVALID_REQUEST');
105
+ expect(result['cards']).toBeUndefined();
106
+ }
107
+ // 纯整数字串('0'/'51')过 coerce 保留 string,进入工具归一 → INVALID_REQUEST 失败事实
108
+ for (const bad of ['abc', '0', '51']) {
109
+ const result = await tools.listActivityPlays.execute!({ limit: bad }, createToolExecContext(reqCtxOf('mall-a')) as never) as Record<string, unknown>;
110
+ expect(result['found'], `limit=${bad}`).toBe(false);
111
+ expect(result['errorCode']).toBe('INVALID_REQUEST');
112
+ expect(result['cards']).toBeUndefined();
113
+ }
114
+ });
115
+
116
+ it('空目录/关键词无匹配:明确空结果事实,无 cards 键,不是错误', async () => {
117
+ const tools = makeTools(listPort([]));
118
+ const empty = await tools.listActivityPlays.execute!({}, createToolExecContext(reqCtxOf('mall-a')) as never) as Record<string, unknown>;
119
+ expect(empty['found']).toBe(false);
120
+ expect(empty['count']).toBe(0);
121
+ expect(empty['noResultsReason']).toContain('暂未登记');
122
+ expect(empty['cards']).toBeUndefined();
123
+
124
+ const kw = await tools.listActivityPlays.execute!({ keyword: '不存在的活动' }, createToolExecContext(reqCtxOf('mall-a')) as never) as Record<string, unknown>;
125
+ expect(kw['noResultsReason']).toContain('不存在的活动');
126
+ expect(kw['cards']).toBeUndefined();
127
+ });
128
+
129
+ it('供给失败分类(errors.ts 单源):配置缺席族 → NOT_CONFIGURED;异常 → PROVIDER_ERROR 不透原始内容', async () => {
130
+ resolvePortMock.mockImplementation(async () => { throw Object.assign(new Error('原始敏感配置细节'), { code: 'PROVIDER_SERVICE_NOT_CONFIGURED' }); });
131
+ const ctx = {} as ServerContext;
132
+ const tools = createActivityPlayTools({ getCtx: () => ctx });
133
+ const result = await tools.listActivityPlays.execute!({}, createToolExecContext(reqCtxOf('mall-a')) as never) as Record<string, unknown>;
134
+ expect(result['errorCode']).toBe('NOT_CONFIGURED');
135
+ expect(JSON.stringify(result)).not.toContain('敏感');
136
+
137
+ resolvePortMock.mockImplementation(async () => { throw new Error('boom 原始异常'); });
138
+ const result2 = await tools.listActivityPlays.execute!({}, createToolExecContext(reqCtxOf('mall-a')) as never) as Record<string, unknown>;
139
+ expect(result2['errorCode']).toBe('PROVIDER_ERROR');
140
+ expect(result2['cards']).toBeUndefined();
141
+ expect(JSON.stringify(result2)).not.toContain('boom');
142
+ });
143
+
144
+ it('无商圈 → SCOPE_REQUIRED 显性失败(不默认其他商圈)', async () => {
145
+ const tools = makeTools(listPort([ITEM]));
146
+ const result = await tools.listActivityPlays.execute!({}, createToolExecContext({ identity: { userId: 'u', source: 'guest' } }) as never) as Record<string, unknown>;
147
+ expect(result['errorCode']).toBe('SCOPE_REQUIRED');
148
+ expect(result['cards']).toBeUndefined();
149
+ });
150
+
151
+ it('上下文隔离:连续两商圈各自解析(目录不同、mallId 各自出口)', async () => {
152
+ const portA = listPort([ITEM]);
153
+ const portB = listPort([ITEM_B]);
154
+ resolvePortMock.mockImplementation(async () => (lastMall === 'mall-a' ? portA : portB) as never);
155
+ let lastMall = 'mall-a';
156
+ const ctx = {} as ServerContext;
157
+ const tools = createActivityPlayTools({ getCtx: () => ctx });
158
+ const a = await tools.listActivityPlays.execute!({}, createToolExecContext(reqCtxOf('mall-a')) as never) as Record<string, unknown>;
159
+ expect((a['cards'] as { data: { mallId: string } }[])[0]?.data.mallId).toBe('mall-a');
160
+
161
+ lastMall = 'mall-b';
162
+ const b = await tools.listActivityPlays.execute!({}, createToolExecContext(reqCtxOf('mall-b')) as never) as Record<string, unknown>;
163
+ expect((b['cards'] as { data: { mallId: string } }[])[0]?.data.mallId).toBe('mall-b');
164
+ // 上一轮成功卡片不残留到本轮失败路径:接下来让供给抛错,b 之后再查 a 失败
165
+ resolvePortMock.mockImplementation(async () => { throw Object.assign(new Error('x'), { code: 'PROVIDER_INSTANCE_DISABLED' }); });
166
+ const fail = await tools.listActivityPlays.execute!({}, createToolExecContext(reqCtxOf('mall-a')) as never) as Record<string, unknown>;
167
+ expect(fail['errorCode']).toBe('NOT_CONFIGURED');
168
+ expect(fail['cards']).toBeUndefined();
169
+ });
170
+ });
171
+
172
+ describe('getActivityPlayDetail', () => {
173
+ it('命中:一张 mode=detail 卡(items 恰一);facts 含状态/时间/说明', async () => {
174
+ const tools = makeTools(listPort([ITEM, ITEM_B]));
175
+ const result = await tools.getActivityPlayDetail.execute!({ activityRef: 'demo:checkin' }, createToolExecContext(reqCtxOf('mall-a')) as never) as Record<string, unknown>;
176
+ expect(result['found']).toBe(true);
177
+ expect(result['activityRef']).toBe('demo:checkin');
178
+ expect(result['statusText']).toBe('未开始');
179
+ expect((result['items'] as unknown[] | undefined)).toBeUndefined(); // detail = 扁平 facts(非列表嵌套)
180
+ const cards = result['cards'] as Array<{ cardType: string; data: { mode: string; items: unknown[] } }>;
181
+ expect(cards).toHaveLength(1);
182
+ expect(cards[0]?.cardType).toBe(ACTIVITY_PLAY_CARD_TYPE);
183
+ expect(cards[0]?.data.mode).toBe('detail');
184
+ expect(cards[0]?.data.items).toHaveLength(1);
185
+ activityPlayCardDataSchema.parse(cards[0]?.data);
186
+ });
187
+
188
+ it('detail 允许返回 disabled(状态说明用),卡 data 不携带 enabled', async () => {
189
+ const disabledItem = { activityRef: 'demo:hidden', title: '停用活动', status: 'disabled' as const, loginRequired: false };
190
+ const tools = makeTools(listPort([disabledItem]));
191
+ const result = await tools.getActivityPlayDetail.execute!({ activityRef: 'demo:hidden' }, createToolExecContext(reqCtxOf('mall-a')) as never) as Record<string, unknown>;
192
+ expect(result['found']).toBe(true);
193
+ expect(result['statusText']).toBe('已停用');
194
+ const card = (result['cards'] as Array<{ data: Record<string, unknown> }>)[0];
195
+ const item = (card?.data['items'] as Array<Record<string, unknown>>)[0];
196
+ expect(item['enabled']).toBeUndefined();
197
+ });
198
+
199
+ it('未知引用 → ACTIVITY_NOT_FOUND 失败事实,无 cards(不猜首项/不造演示详情)', async () => {
200
+ const tools = makeTools(listPort([ITEM]));
201
+ const result = await tools.getActivityPlayDetail.execute!({ activityRef: 'demo:none' }, createToolExecContext(reqCtxOf('mall-a')) as never) as Record<string, unknown>;
202
+ expect(result['found']).toBe(false);
203
+ expect(result['errorCode']).toBe('ACTIVITY_NOT_FOUND');
204
+ expect(result['cards']).toBeUndefined();
205
+ });
206
+
207
+ it('非法 activityRef → INVALID_REQUEST(契约引用形状单源)', async () => {
208
+ const tools = makeTools(listPort([ITEM]));
209
+ for (const bad of ['', ' ', 'bad ref!', 'x'.repeat(129)]) {
210
+ const result = await tools.getActivityPlayDetail.execute!({ activityRef: bad }, createToolExecContext(reqCtxOf('mall-a')) as never) as Record<string, unknown>;
211
+ expect(result['errorCode'], JSON.stringify(bad)).toBe('INVALID_REQUEST');
212
+ expect(result['cards']).toBeUndefined();
213
+ }
214
+ });
215
+
216
+ it('评审返修回归:数字/布尔形态合法字面量引用(原始字串保留,数字串同型不撞车)', async () => {
217
+ const weirdRefs = ['1.2', 'true', '0.12345', '42'];
218
+ const items = weirdRefs.map((ref) => ({ ...ITEM, activityRef: ref }));
219
+ const tools = makeTools(listPort(items));
220
+ for (const ref of weirdRefs) {
221
+ const result = await tools.getActivityPlayDetail.execute!({ activityRef: ref }, createToolExecContext(reqCtxOf('mall-a')) as never) as Record<string, unknown>;
222
+ expect(result['found'], `activityRef=${ref}`).toBe(true);
223
+ expect(result['activityRef']).toBe(ref);
224
+ const cards = result['cards'] as Array<{ data: { items: Array<{ activityRef: string }> } }>;
225
+ expect(cards[0]?.data.items[0]?.activityRef).toBe(ref); // 卡 data 原样保留字面量
226
+ }
227
+ });
228
+
229
+ it('评审返修二轮:数字同型不同值引用不串答(JSON 转换已移除——1.20 不再折叠成 1.2、1e3 不再折叠成 1000)', async () => {
230
+ // 目录同时含 1.2/1.20 与 1e3/1000 四个独立活动:每个引用必须精确命中自己
231
+ const refs = ['1.2', '1.20', '1e3', '1000'];
232
+ const items = refs.map((ref) => ({ ...ITEM, activityRef: ref, title: `活动${ref}` }));
233
+ const tools = makeTools(listPort(items));
234
+ for (const ref of refs) {
235
+ const result = await tools.getActivityPlayDetail.execute!({ activityRef: ref }, createToolExecContext(reqCtxOf('mall-a')) as never) as Record<string, unknown>;
236
+ expect(result['found'], `activityRef=${ref}`).toBe(true);
237
+ expect(result['activityRef']).toBe(ref);
238
+ expect(result['title']).toBe(`活动${ref}`); // 撞车即串答——此处必须各自命中
239
+ }
240
+ });
241
+
242
+ it('名称→引用不隐式回退:非 ref 形状 = INVALID_REQUEST;合法形状未知 = NOT_FOUND(无首项/演示回退)', async () => {
243
+ const tools = makeTools(listPort([ITEM]));
244
+ // 标题字面量不是 activityRef(形状非法——技能引导模型先查列表拿引用,不猜)
245
+ const byTitle = await tools.getActivityPlayDetail.execute!({ activityRef: '幸运大转盘' }, createToolExecContext(reqCtxOf('mall-a')) as never) as Record<string, unknown>;
246
+ expect(byTitle['errorCode']).toBe('INVALID_REQUEST');
247
+ // 形状合法但目录中不存在
248
+ const byUnknownRef = await tools.getActivityPlayDetail.execute!({ activityRef: 'demo:none' }, createToolExecContext(reqCtxOf('mall-a')) as never) as Record<string, unknown>;
249
+ expect(byUnknownRef['errorCode']).toBe('ACTIVITY_NOT_FOUND');
250
+ });
251
+ });
package/tsconfig.json ADDED
@@ -0,0 +1,8 @@
1
+ {
2
+ "extends": "../../tsconfig.base.json",
3
+ "compilerOptions": {
4
+ "jsx": "react-jsx",
5
+ "types": ["node"]
6
+ },
7
+ "include": ["src", "tests"]
8
+ }
package/tsup.config.ts ADDED
@@ -0,0 +1,27 @@
1
+ import { defineConfig } from 'tsup';
2
+
3
+ export default defineConfig({
4
+ entry: {
5
+ index: 'src/index.ts',
6
+ 'server/index': 'src/server/index.ts',
7
+ 'client/index': 'src/client/index.ts',
8
+ },
9
+ format: ['esm'],
10
+ target: 'node20',
11
+ platform: 'node',
12
+ outDir: 'dist',
13
+ clean: true,
14
+ sourcemap: false,
15
+ dts: { compilerOptions: { incremental: false } },
16
+ external: [
17
+ '@tbox.cn/app-agent-sdk-client',
18
+ '@tbox.cn/app-agent-sdk-server',
19
+ '@tbox.cn/app-contracts',
20
+ '@tbox.cn/app-contracts-mall',
21
+ 'react',
22
+ 'react-dom',
23
+ 'zod',
24
+ '@mastra/core',
25
+ 'express',
26
+ ],
27
+ });