@tbox.cn/app-module-alipay-activity 0.2.3

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 (44) hide show
  1. package/AGENTS.md +16 -0
  2. package/LICENSE +21 -0
  3. package/README.md +48 -0
  4. package/dist/bumpin-VKHLYCKG.css +527 -0
  5. package/dist/chunk-RM7IUA3M.js +634 -0
  6. package/dist/client/index.d.ts +11 -0
  7. package/dist/client/index.js +235 -0
  8. package/dist/index.d.ts +7 -0
  9. package/dist/index.js +26 -0
  10. package/dist/linked-card-background-MVGUOJ7J.jpg +0 -0
  11. package/dist/server/index.d.ts +224 -0
  12. package/dist/server/index.js +28 -0
  13. package/package.json +69 -0
  14. package/schemas/credentials/alipay-open-v1.json +12 -0
  15. package/skills/alipay-activity/SKILL.md +59 -0
  16. package/src/client/assets/linked-card-background.jpg +0 -0
  17. package/src/client/assets.d.ts +10 -0
  18. package/src/client/cards/bumpin-activity/index.tsx +213 -0
  19. package/src/client/components/ImageWithFallback.tsx +37 -0
  20. package/src/client/index.ts +18 -0
  21. package/src/client/styles/bumpin.css +527 -0
  22. package/src/client/utils/sanitize-activity-html.ts +40 -0
  23. package/src/index.ts +1 -0
  24. package/src/server/cards/bumpin-activity/meta.ts +44 -0
  25. package/src/server/cards/bumpin-activity/samples.ts +164 -0
  26. package/src/server/handler.ts +87 -0
  27. package/src/server/index.ts +79 -0
  28. package/src/server/integrations/alipay/adapter.ts +210 -0
  29. package/src/server/integrations/alipay/client.ts +127 -0
  30. package/src/server/integrations/alipay/provider.ts +9 -0
  31. package/src/server/ports.ts +68 -0
  32. package/src/server/tools.ts +212 -0
  33. package/tbox.module.json +39 -0
  34. package/tests/adapter.test.ts +178 -0
  35. package/tests/bumpin-card-status.test.tsx +80 -0
  36. package/tests/client.test.ts +93 -0
  37. package/tests/intent-routing.test.ts +118 -0
  38. package/tests/ports.test.ts +160 -0
  39. package/tests/pretool-routing.test.ts +37 -0
  40. package/tests/samples.test.ts +29 -0
  41. package/tests/skill.test.ts +39 -0
  42. package/tests/tools.test.ts +193 -0
  43. package/tsconfig.json +8 -0
  44. package/tsup.config.ts +36 -0
@@ -0,0 +1,118 @@
1
+ /**
2
+ * bumpin 意图路由回归(顶层确定性档:exact 品牌固定句直出,语义问句走 LLM 编排):
3
+ * - 误命中:含「支付宝」的无关长句(充值/付款/互动活动取消类)不路由到 bumpin;
4
+ * - exact:品牌固定句(碰出惊喜/碰一下/碰一碰)整句全等直出 detail 卡;
5
+ * - 语义问句(「支付宝碰一下」/「帮我看看碰出惊喜活动怎么参加」)不再 BM25 直出——
6
+ * 走 LLM → getBumpInActivity 工具编排(复合句不被 detail 卡吞半句);
7
+ * - 洋葱守卫:prefix 误送达 content 无域词时 handler 放行(continueWith 原文、零卡零文案不吞轮)。
8
+ */
9
+ import { describe, expect, it, vi } from 'vitest';
10
+ import { createServerContext, matchIntent } from '@tbox.cn/app-sdk/server';
11
+ import type { IntentRoute } from '@tbox.cn/app-sdk/server';
12
+ import { PROMOTION_ACTIVITY_ROUTING_POLICY } from '@tbox.cn/app-contracts-mall';
13
+ import { BUMPIN_INTENTS, createAlipayActivityHandler } from '../src/server/handler';
14
+
15
+ vi.mock('../src/server/ports', async (importOriginal) => {
16
+ const actual = await importOriginal<typeof import('../src/server/ports')>();
17
+ return { ...actual, resolveAlipayBumpInService: vi.fn() };
18
+ });
19
+ import { resolveAlipayBumpInService } from '../src/server/ports';
20
+
21
+ /** 外层意图路由测试表(镜像 collectIntentRoutes 装配语义:id/handlerId/action/match 同构) */
22
+ const BUMPIN_TEST_ROUTES: IntentRoute[] = Object.values(BUMPIN_INTENTS).map(({ patterns }) => ({
23
+ id: `alipay-activity:${patterns[0]}`,
24
+ keywords: [...patterns],
25
+ handlerId: 'alipay-activity',
26
+ action: 'intent',
27
+ match: 'exact',
28
+ }));
29
+
30
+ const testRequestContext = () => ({
31
+ identity: { userId: 'u_1', source: 'dev' as const },
32
+ attributes: { mall: { miniAppId: 'app', mallId: 'mall-1' } },
33
+ });
34
+
35
+ describe('bumpin 意图路由(顶层确定性档)', () => {
36
+ it('含「支付宝」的无关长句不再误入 bumpin 路由', () => {
37
+ expect(matchIntent(BUMPIN_TEST_ROUTES, '支付宝哪里可以充值')).toBeUndefined();
38
+ expect(matchIntent(BUMPIN_TEST_ROUTES, '我用支付宝付钱了')).toBeUndefined();
39
+ expect(matchIntent(BUMPIN_TEST_ROUTES, '支付宝互动活动怎么取消参加')).toBeUndefined();
40
+ });
41
+
42
+ it('品牌固定句 exact 直出(整句全等,trim 容差)', () => {
43
+ expect(matchIntent(BUMPIN_TEST_ROUTES, '碰出惊喜')?.handlerId).toBe('alipay-activity');
44
+ expect(matchIntent(BUMPIN_TEST_ROUTES, '碰一下')?.handlerId).toBe('alipay-activity');
45
+ expect(matchIntent(BUMPIN_TEST_ROUTES, '碰一碰')?.handlerId).toBe('alipay-activity');
46
+ expect(matchIntent(BUMPIN_TEST_ROUTES, ' 碰出惊喜 ')?.handlerId).toBe('alipay-activity');
47
+ });
48
+
49
+ it('语义问句不再 BM25 截断(复合句回归锚:走 LLM 工具编排承接)', () => {
50
+ expect(matchIntent(BUMPIN_TEST_ROUTES, '支付宝碰一下')).toBeUndefined();
51
+ expect(matchIntent(BUMPIN_TEST_ROUTES, '帮我看看碰出惊喜活动怎么参加')).toBeUndefined();
52
+ expect(matchIntent(BUMPIN_TEST_ROUTES, '我的惊喜活动还有吗')).toBeUndefined();
53
+ expect(matchIntent(BUMPIN_TEST_ROUTES, '碰一下和领券能同时参加吗')).toBeUndefined();
54
+ });
55
+ });
56
+
57
+ describe('bumpin handler 洋葱守卫', () => {
58
+ it('误命中 content(无域词)放行 LLM:continueWith 原文、零卡零文案', async () => {
59
+ const ctx = createServerContext();
60
+ const handler = createAlipayActivityHandler(ctx);
61
+
62
+ const result = await handler.handle('intent', { content: '支付宝怎么解绑' }, ctx, testRequestContext());
63
+
64
+ expect(result.cards).toHaveLength(0);
65
+ expect(result.text ?? '').toBe('');
66
+ expect(result.continueWith?.content).toBe('支付宝怎么解绑');
67
+ });
68
+
69
+ it('域词 content 越过守卫(未装配 provider 时走既有缺省文案,不因守卫吞轮)', async () => {
70
+ const ctx = createServerContext();
71
+ const handler = createAlipayActivityHandler(ctx);
72
+
73
+ const result = await handler.handle('intent', { content: '碰出惊喜' }, ctx, testRequestContext());
74
+
75
+ expect(result.cards).toHaveLength(0);
76
+ expect(result.text).toBe('碰出惊喜活动能力未装配,请联系运营配置凭证');
77
+ });
78
+
79
+ it('活动中心分流:专属 provider scope 统一返回联单活动卡', async () => {
80
+ vi.mocked(resolveAlipayBumpInService).mockResolvedValue({
81
+ listActivities: async () => ({
82
+ items: [{
83
+ activityRef: 'alipay:bumpin:scheme-1',
84
+ title: '碰一下联单赢券',
85
+ linkedOrder: true,
86
+ registrationRequired: false,
87
+ offerRefs: [],
88
+ sessions: [],
89
+ }],
90
+ hasMore: false,
91
+ }),
92
+ } as never);
93
+ const ctx = createServerContext();
94
+ ctx.services.register(PROMOTION_ACTIVITY_ROUTING_POLICY, () => true);
95
+ const handler = createAlipayActivityHandler(ctx);
96
+ const reqCtx = {
97
+ ...testRequestContext(),
98
+ credentials: { token: 'target-token', provider: 'target' },
99
+ };
100
+
101
+ const result = await handler.handle('activity-router', { content: '活动中心' }, ctx, reqCtx);
102
+
103
+ expect(vi.mocked(resolveAlipayBumpInService)).toHaveBeenCalled();
104
+ expect(result.cards).toHaveLength(1);
105
+ expect(result.cards[0]?.cardType).toBe('promotion-bumpin-activity');
106
+ expect(result.cards[0]?.data).toMatchObject({ title: '碰一下联单赢券', tagLabel: '碰一下联单' });
107
+ });
108
+
109
+ it('活动中心分流:未启用专属策略时放行给原 promotion 活动路径', async () => {
110
+ const ctx = createServerContext();
111
+ const handler = createAlipayActivityHandler(ctx);
112
+
113
+ const result = await handler.handle('activity-router', { content: '活动中心' }, ctx, testRequestContext());
114
+
115
+ expect(result.cards).toHaveLength(0);
116
+ expect(result.continueWith?.content).toBe('活动中心');
117
+ });
118
+ });
@@ -0,0 +1,160 @@
1
+ /**
2
+ * bumpin 配置面直读测试(T1.3 迁移:ctx.providers.resolve → config/bumpin.json):
3
+ * - 注入/缺文件/缺字段/解析失败 fail-soft 四分支
4
+ * - credentialRef/linkedCardBackgroundUrl 可选字段透传
5
+ * - resolveAlipayBumpInService 契约:配置在场即构造 service(无 provider 装配语义)
6
+ */
7
+ import { describe, expect, it, beforeEach, afterEach } from 'vitest';
8
+ import { mkdirSync, mkdtempSync, writeFileSync, rmSync } from 'node:fs';
9
+ import { tmpdir } from 'node:os';
10
+ import path from 'node:path';
11
+ import {
12
+ configureAlipayBumpIn,
13
+ readAlipayBumpInConfig,
14
+ resolveAlipayBumpInService,
15
+ } from '../src/server/ports.js';
16
+ import type { ServerContext } from '@tbox.cn/app-sdk/server';
17
+
18
+ /** 最小 ctx 桩(logger warn 收集;其余槽位不触达) */
19
+ function ctxStub(): { ctx: ServerContext; warns: string[] } {
20
+ const warns: string[] = [];
21
+ const ctx = {
22
+ logger: {
23
+ warn: (...args: unknown[]) => warns.push(args.map(String).join(' ')),
24
+ info: () => {},
25
+ debug: () => {},
26
+ },
27
+ } as unknown as ServerContext;
28
+ return { ctx, warns };
29
+ }
30
+
31
+ const GOOD_CFG = { gateway: 'https://openapipre.alipay.com/gateway.do', actSchemeId: 'AS_TEST_1' };
32
+
33
+ describe('readAlipayBumpInConfig:fail-soft 四分支', () => {
34
+ let dir: string;
35
+ let file: string;
36
+
37
+ beforeEach(() => {
38
+ dir = mkdtempSync(path.join(tmpdir(), 'bumpin-'));
39
+ file = path.join(dir, 'bumpin.json');
40
+ });
41
+ afterEach(() => {
42
+ rmSync(dir, { recursive: true, force: true });
43
+ configureAlipayBumpIn(''); // 复位单例(空串路径恒不存在 = 未注入语义)
44
+ });
45
+
46
+ it('未注入 → null(零 IO)', () => {
47
+ configureAlipayBumpIn('');
48
+ expect(readAlipayBumpInConfig()).toBeNull();
49
+ });
50
+
51
+ it('注入但文件缺席 → null', () => {
52
+ configureAlipayBumpIn(path.join(dir, 'absent.json'));
53
+ expect(readAlipayBumpInConfig()).toBeNull();
54
+ });
55
+
56
+ it('必填字段齐全 → 全量返回 + 可选字段透传', () => {
57
+ writeFileSync(file, JSON.stringify({ ...GOOD_CFG, linkedCardBackgroundUrl: '/assets/bg.png', credentialRef: 'secret://ALIPAY_BUMPIN' }));
58
+ configureAlipayBumpIn(file);
59
+ expect(readAlipayBumpInConfig()).toEqual({
60
+ ...GOOD_CFG,
61
+ linkedCardBackgroundUrl: '/assets/bg.png',
62
+ credentialRef: 'secret://ALIPAY_BUMPIN',
63
+ });
64
+ });
65
+
66
+ it('gateway/actSchemeId 缺失 → null + warn', () => {
67
+ const { ctx, warns } = ctxStub();
68
+ writeFileSync(file, JSON.stringify({ gateway: 'https://x' }));
69
+ configureAlipayBumpIn(file);
70
+ expect(readAlipayBumpInConfig(ctx)).toBeNull();
71
+ expect(warns.join()).toContain('actSchemeId');
72
+ });
73
+
74
+ it('JSON 解析失败 → null + warn', () => {
75
+ const { ctx, warns } = ctxStub();
76
+ writeFileSync(file, '{broken');
77
+ configureAlipayBumpIn(file);
78
+ expect(readAlipayBumpInConfig(ctx)).toBeNull();
79
+ expect(warns.join()).toContain('解析失败');
80
+ });
81
+
82
+ it('可选字段空白值剔除(只回必填两键)', () => {
83
+ writeFileSync(file, JSON.stringify({ ...GOOD_CFG, linkedCardBackgroundUrl: '', credentialRef: '' }));
84
+ configureAlipayBumpIn(file);
85
+ expect(readAlipayBumpInConfig()).toEqual(GOOD_CFG);
86
+ });
87
+ });
88
+
89
+ describe('resolveAlipayBumpInService:配置在场即构造', () => {
90
+ let dir: string;
91
+ beforeEach(() => {
92
+ dir = mkdtempSync(path.join(tmpdir(), 'bumpin-svc-'));
93
+ });
94
+ afterEach(() => {
95
+ rmSync(dir, { recursive: true, force: true });
96
+ configureAlipayBumpIn('');
97
+ });
98
+
99
+ it('配置缺席 → null(工具层静默降级)', async () => {
100
+ configureAlipayBumpIn('');
101
+ expect(await resolveAlipayBumpInService(ctxStub().ctx)).toBeNull();
102
+ });
103
+
104
+ it('配置在场 → AlipayBumpInService 实例(listActivities 可用面)', async () => {
105
+ // 凭证链:ALIPAY_BUMPIN env(真源 .real-env/credentials;测试注入非占位重构造值)
106
+ const prev = process.env.ALIPAY_BUMPIN;
107
+ process.env.ALIPAY_BUMPIN = JSON.stringify({
108
+ value: { appId: '2021000000000000', privateKey: 'k-test', alipayPublicKey: 'pk-test' },
109
+ });
110
+ try {
111
+ const file = path.join(dir, 'bumpin.json');
112
+ writeFileSync(file, JSON.stringify(GOOD_CFG));
113
+ configureAlipayBumpIn(file);
114
+ const svc = await resolveAlipayBumpInService(ctxStub().ctx);
115
+ expect(svc).toBeTruthy();
116
+ expect(typeof (svc as unknown as { listActivities: unknown }).listActivities).toBe('function');
117
+ } finally {
118
+ if (prev === undefined) delete process.env.ALIPAY_BUMPIN;
119
+ else process.env.ALIPAY_BUMPIN = prev;
120
+ }
121
+ });
122
+
123
+ it('凭证缺失(ALIPAY_BUMPIN 不在场)→ null(fail-soft 同链)', async () => {
124
+ const prev = process.env.ALIPAY_BUMPIN;
125
+ delete process.env.ALIPAY_BUMPIN;
126
+ try {
127
+ const file = path.join(dir, 'bumpin.json');
128
+ writeFileSync(file, JSON.stringify(GOOD_CFG));
129
+ configureAlipayBumpIn(file);
130
+ expect(await resolveAlipayBumpInService(ctxStub().ctx)).toBeNull();
131
+ } finally {
132
+ if (prev !== undefined) process.env.ALIPAY_BUMPIN = prev;
133
+ }
134
+ });
135
+
136
+ it('文件通道(v2):bumpin.json 同目录 credentials/ 优先于 env(免 source env 一期部署)', async () => {
137
+ const prev = process.env.ALIPAY_BUMPIN;
138
+ process.env.ALIPAY_BUMPIN = JSON.stringify({
139
+ value: { appId: 'from-env', privateKey: 'k-env', alipayPublicKey: 'pk-env' },
140
+ });
141
+ try {
142
+ const file = path.join(dir, 'bumpin.json');
143
+ writeFileSync(file, JSON.stringify(GOOD_CFG));
144
+ mkdirSync(path.join(dir, 'credentials'), { recursive: true });
145
+ writeFileSync(
146
+ path.join(dir, 'credentials', 'alipay-bumpin.json'),
147
+ JSON.stringify({ scope: {}, type: 'alipay-open-v1', value: { appId: '2021000000000000', privateKey: 'k-test', alipayPublicKey: 'pk-test' } }),
148
+ );
149
+ configureAlipayBumpIn(file);
150
+ const svc = await resolveAlipayBumpInService(ctxStub().ctx);
151
+ expect(svc).toBeTruthy(); // 文件命中 → AlipaySdk 构造(非 null)
152
+ // env 源注入(正源)构造 AlipaySdk 也是非 null——用 appId 判定不可行,改断言类型面
153
+ expect(typeof (svc as unknown as { listActivities: unknown }).listActivities).toBe('function');
154
+ } finally {
155
+ rmSync(path.join(dir, 'credentials'), { recursive: true, force: true });
156
+ if (prev === undefined) delete process.env.ALIPAY_BUMPIN;
157
+ else process.env.ALIPAY_BUMPIN = prev;
158
+ }
159
+ });
160
+ });
@@ -0,0 +1,37 @@
1
+ /**
2
+ * bumpin preTool 路由验收:碰词族 keywords 命中(含缺字口语变体「碰惊喜活动」)、
3
+ * 他域问句不误命中(词表纯命中——description 不入路由索引)。
4
+ * (镜像 server/index.ts bumpInPreTool 声明:真实工具实例 + 同词表)
5
+ */
6
+ import { describe, expect, it } from 'vitest';
7
+ import { definePreTool, selectPreTools } from '@tbox.cn/app-sdk/server';
8
+ import { z } from 'zod';
9
+ import { createBumpInTools } from '../src/server/tools';
10
+
11
+ const tools = createBumpInTools({ getCtx: () => undefined as never });
12
+
13
+ const bumpInPreTool = definePreTool(tools.getBumpInActivity, {
14
+ routing: {
15
+ mode: 'keywords',
16
+ terms: ['碰一碰', '碰一下', '碰出惊喜', '碰惊喜', '惊喜活动', 'NFC'],
17
+ },
18
+ decide: ({ text }) =>
19
+ text && text.trim().length > 0
20
+ ? { decision: 'run', args: {} }
21
+ : { decision: 'skip', reason: '空文本' },
22
+ silent: true,
23
+ });
24
+
25
+ describe('bumpInPreTool 路由', () => {
26
+ it('碰词族问句命中(含缺字变体「碰惊喜活动」)', () => {
27
+ for (const q of ['碰一碰活动进度怎么样', '碰惊喜活动', '碰出惊喜奖励是什么', '碰一下怎么参加', '商场有 NFC 活动吗']) {
28
+ expect(selectPreTools(q, [bumpInPreTool]).map((d) => d.tool.id)).toEqual(['getBumpInActivity']);
29
+ }
30
+ });
31
+
32
+ it('他域/无关问句不误命中(词表纯命中)', () => {
33
+ for (const q of ['退换货政策是什么', '现在有什么优惠券可以领', '我的会员卡', '停车费多少']) {
34
+ expect(selectPreTools(q, [bumpInPreTool])).toEqual([]);
35
+ }
36
+ });
37
+ });
@@ -0,0 +1,29 @@
1
+ /**
2
+ * samples 双断言(沉淀自 mall dev-gallery 首页场景画廊):
3
+ * 全样本 dataSchema.safeParse 通过 + findSampleShapeViolations 无越界键(样本即契约)。
4
+ */
5
+ import { describe, expect, it } from 'vitest';
6
+ import { findSampleShapeViolations } from '@tbox.cn/app-sdk/server';
7
+ import meta from '../src/server/cards/bumpin-activity/meta';
8
+
9
+ describe('alipay-activity samples 双断言(样本即契约)', () => {
10
+ it('promotion-bumpin-activity: 全样本过 schema + shape 无越界', () => {
11
+ expect(meta.samples?.length ?? 0).toBeGreaterThan(0);
12
+ expect(findSampleShapeViolations(meta).violations).toEqual([]);
13
+ for (const s of meta.samples ?? []) {
14
+ expect(
15
+ meta.dataSchema.safeParse(s.data).success,
16
+ s.label,
17
+ ).toBe(true);
18
+ }
19
+ });
20
+
21
+ it('形态覆盖:detail × banner 两模式、steps × bar 两进度样式均在场', () => {
22
+ const serialized = JSON.stringify(meta.samples ?? []);
23
+ expect(serialized).toContain('"mode":"detail"');
24
+ expect(serialized).toContain('"mode":"banner"');
25
+ expect(serialized).toContain('"progressStyle":"steps"');
26
+ expect(serialized).toContain('"progressStyle":"bar"');
27
+ expect(meta.samples).toHaveLength(16);
28
+ });
29
+ });
@@ -0,0 +1,39 @@
1
+ /**
2
+ * alipay-activity 文件 skill 装配验收——loadModuleSkills 经 workspace link 解析包根 skills/,
3
+ * 声明式通道填回 serverModule.skills;routingTerms 为窄品牌词族(与营销券词零交集)。
4
+ */
5
+ import { describe, expect, it } from 'vitest';
6
+ import { serverModule } from '../src/server/index';
7
+
8
+ type LoadedSkill = { name: string; description: string; routingTerms: string[]; instructions: string };
9
+
10
+ describe('alipay-activity skills 装配', () => {
11
+ const skills = ((serverModule as { skills?: Record<string, LoadedSkill> }).skills ?? {});
12
+
13
+ it('skills 含 alipay-activity(frontmatter name + 目录名一致)', () => {
14
+ expect(Object.keys(skills)).toContain('alipay-activity');
15
+ expect(skills['alipay-activity']!.description.length).toBeGreaterThan(0);
16
+ expect(skills['alipay-activity']!.instructions).toContain('碰出惊喜');
17
+ });
18
+
19
+ it('routingTerms 窄品牌词族且不含营销券词(券归 promotion 域)', () => {
20
+ expect(skills['alipay-activity']!.routingTerms).toEqual([
21
+ '碰一碰',
22
+ '碰一下',
23
+ '碰出惊喜',
24
+ '惊喜活动',
25
+ 'NFC',
26
+ ]);
27
+ expect(skills['alipay-activity']!.routingTerms.some((t) => t.includes('券'))).toBe(false);
28
+ });
29
+
30
+ it('SOP 含工具单源与红线(不代用户物理动作 / Banner 工具对话不调 / pre-tool 块承接)', () => {
31
+ expect(skills['alipay-activity']!.instructions).toContain('getBumpInActivity');
32
+ expect(skills['alipay-activity']!.instructions).toContain('不代用户操作');
33
+ expect(skills['alipay-activity']!.instructions).toContain('对话轮');
34
+ expect(skills['alipay-activity']!.instructions).toContain('listCoupons');
35
+ // 2026-08-31:bumpin preTool 上线——SOP 承接 pre-tool 注入块语义(有块直答、无块才调工具)
36
+ expect(skills['alipay-activity']!.instructions).toContain('预查询');
37
+ expect(skills['alipay-activity']!.instructions).toContain('无需重复调用工具');
38
+ });
39
+ });
@@ -0,0 +1,193 @@
1
+ import { describe, expect, it, vi } from 'vitest';
2
+ import { toBumpInCardData, parseAlipayRichText, createBumpInTools } from '../src/server/tools.js';
3
+ import type { PromotionActivityDetail } from '@tbox.cn/app-contracts-mall';
4
+ import { createServerContext, createToolExecContext } from '@tbox.cn/app-sdk/server';
5
+ import { createAlipayActivityHandler } from '../src/server/handler.js';
6
+
7
+ // mock ports 的服务解析(工具内部 import;测试注入)
8
+ vi.mock('../src/server/ports', async (importOriginal) => {
9
+ const actual = await importOriginal<typeof import('../src/server/ports')>();
10
+ return { ...actual, resolveAlipayBumpInService: vi.fn() };
11
+ });
12
+ import { resolveAlipayBumpInService } from '../src/server/ports.js';
13
+
14
+ /** 最小 detail 构造(必填面:activityRef/title/registrationRequired/offerRefs/sessions) */
15
+ function buildDetail(overrides: Partial<PromotionActivityDetail> = {}): PromotionActivityDetail {
16
+ return {
17
+ activityRef: 'act-001',
18
+ title: '会员日抽奖',
19
+ registrationRequired: false,
20
+ offerRefs: [],
21
+ sessions: [],
22
+ ...overrides,
23
+ };
24
+ }
25
+
26
+ describe('toBumpInCardData 投影(联单/普通双形态)', () => {
27
+ it('普通活动 → progressStyle=bar、无联单标签、coverUrl 透传', () => {
28
+ const card = toBumpInCardData(buildDetail({ coverUrl: 'https://img/c.png' }), 'banner');
29
+ expect(card.progressStyle).toBe('bar');
30
+ expect(card.tagLabel).toBeUndefined();
31
+ expect(card.coverUrl).toBe('https://img/c.png');
32
+ expect(card.backgroundUrl).toBeUndefined();
33
+ expect(card.mode).toBe('banner');
34
+ });
35
+
36
+ it('联单活动(linkedOrder=true,标题无关键字)→ progressStyle=steps + 联单标签 + backgroundUrl 透传', () => {
37
+ const card = toBumpInCardData(
38
+ buildDetail({ title: 'XX广场 | 碰出惊喜', linkedOrder: true, guide: { steps: [], conditions: ['规则A', '目标:5笔,已完成:1笔'], notice: undefined } }),
39
+ 'banner',
40
+ 'https://img/bg.png',
41
+ );
42
+ expect(card.progressStyle).toBe('steps');
43
+ expect(card.tagLabel).toBe('碰一下联单');
44
+ expect(card.backgroundUrl).toBe('https://img/bg.png');
45
+ expect(card.coverUrl).toBeUndefined();
46
+ expect(card.totalProgress).toBe('5');
47
+ expect(card.currentProgress).toBe('1');
48
+ expect(card.progressUnit).toBe('笔');
49
+ });
50
+
51
+ it('标题含「联单」但 linkedOrder 缺省 → 不再按标题判定,progressStyle=bar(关键字判定已废弃)', () => {
52
+ const card = toBumpInCardData(
53
+ buildDetail({ title: '碰一下联单赢券', guide: { steps: [], conditions: ['规则A', '目标:5笔,已完成:1笔'] } }),
54
+ 'banner',
55
+ 'https://img/bg.png',
56
+ );
57
+ expect(card.progressStyle).toBe('bar');
58
+ expect(card.tagLabel).toBeUndefined();
59
+ expect(card.backgroundUrl).toBeUndefined();
60
+ });
61
+
62
+ it('actStatus 投影:detail.activityStatus 词表内透传;缺省/未知兜底 PROCESSING(终态必须显式下发)', () => {
63
+ expect(toBumpInCardData(buildDetail({ activityStatus: 'NOT_START' }), 'detail').actStatus).toBe('NOT_START');
64
+ expect(toBumpInCardData(buildDetail({ activityStatus: 'FINISH' }), 'detail').actStatus).toBe('FINISH');
65
+ expect(toBumpInCardData(buildDetail({ activityStatus: 'RECEIVED' }), 'detail').actStatus).toBe('RECEIVED');
66
+ expect(toBumpInCardData(buildDetail(), 'detail').actStatus).toBe('PROCESSING');
67
+ expect(toBumpInCardData(buildDetail({ activityStatus: 'ONGOING' }), 'detail').actStatus).toBe('PROCESSING');
68
+ });
69
+
70
+ it('支付宝富文本解析 → 纯文本(subtitle 投影 mainTitle)', () => {
71
+ expect(parseAlipayRichText('#{{"color":"#E84749","customStyle":true,"text":"2"}}#')).toBe('2');
72
+ expect(toBumpInCardData(buildDetail({ subtitle: '#{{"color":"#E84749","text":"满减"}}#' }), 'detail').mainTitle).toBe('满减');
73
+ });
74
+
75
+ it('奖励 JSON 异常时保持空数组,不补造演示奖品', () => {
76
+ const card = toBumpInCardData(
77
+ buildDetail({ guide: { steps: [], conditions: [], notice: '{broken' } }),
78
+ 'detail',
79
+ );
80
+ expect(card.vouchers).toEqual([]);
81
+ });
82
+ });
83
+
84
+ describe('身份轴与登录轴门禁(SPEC-5:P4-3 修复 + 匿名只拦登录)', () => {
85
+ const stubDetail = (): PromotionActivityDetail =>
86
+ buildDetail({ title: '碰出惊喜·联单赢券', subtitle: 'more', description: 'desc', coverUrl: 'https://img/c.png', guide: { steps: [], conditions: [], notice: undefined } });
87
+
88
+ const stubService = () => ({ listActivities: async () => ({ items: [stubDetail()], nextCursor: undefined }) });
89
+
90
+ const ctxWith = (identity: { userId: string; source: 'dev' | 'external' | 'anonymous' } | null, gate?: unknown) => {
91
+ const ctx = createServerContext();
92
+ Object.assign(ctx, {
93
+ services: gate ? { resolve: (key: string) => (key === 'member.status' ? gate : undefined) } : {},
94
+ });
95
+ return {
96
+ ctx,
97
+ execCtx: (source: 'dev' | 'external' | 'anonymous' = 'dev') =>
98
+ createToolExecContext({
99
+ identity: { userId: identity?.userId ?? 'u_bump', source: identity?.source ?? 'dev' },
100
+ attributes: { mall: { miniAppId: 'app', mallId: 'mall-1' } },
101
+ ...(identity?.source === 'external'
102
+ ? { credentials: { token: 't', provider: 'alipay-iap', attributes: { openid: 'o_1' } } }
103
+ : {}),
104
+ }) as never,
105
+ };
106
+ };
107
+
108
+ it('execute 收 execCtx:真实 reqCtx → mock service 收到 requestContext.credentials(身份轴修复)', async () => {
109
+ const service = stubService();
110
+ const listActivities = vi.fn(service.listActivities);
111
+ vi.mocked(resolveAlipayBumpInService).mockResolvedValue({ listActivities } as never);
112
+ const { ctx, execCtx } = ctxWith({ userId: '2088_ext', source: 'external' });
113
+ const tools = createBumpInTools(() => ctx);
114
+ const result = (await tools.getBumpInActivity.execute!({} as never, execCtx('external'))) as {
115
+ cards?: { cardType: string }[];
116
+ };
117
+ expect(result.cards?.[0]?.cardType).toBe('promotion-bumpin-activity');
118
+ const [q] = listActivities.mock.calls[0]!;
119
+ expect((q as { subjectId: string }).subjectId).toBe('2088_ext');
120
+ // 身份轴:requestContext 携带真实 credentials(不再是伪造 userId/openId 注入)
121
+ expect((q as { requestContext: { credentials?: { provider: string } } }).requestContext.credentials?.provider).toBe('alipay-iap');
122
+ });
123
+
124
+ // member.status 对匿名 = unauthenticated(login 卡形态;匿名无会员态可言)
125
+ const loginGate = async () => ({ outcome: 'unauthenticated' as const, loginUrl: 'alipays://login' });
126
+
127
+ it('匿名 → login 卡(登录轴门禁,只拦匿名不拦未入会)', async () => {
128
+ const service = stubService();
129
+ const listActivities = vi.fn(service.listActivities);
130
+ vi.mocked(resolveAlipayBumpInService).mockResolvedValue({ listActivities } as never);
131
+ const { ctx, execCtx } = ctxWith({ userId: 'u_anon', source: 'anonymous' }, loginGate);
132
+ const tools = createBumpInTools(() => ctx);
133
+ const result = (await tools.getBumpInActivity.execute!({} as never, execCtx('anonymous'))) as {
134
+ found: boolean;
135
+ cards?: { cardType: string; data: Record<string, unknown> }[];
136
+ };
137
+ expect(result.found).toBe(false);
138
+ expect(result.cards?.[0]?.cardType).toBe('member-login-cta');
139
+ expect(listActivities).not.toHaveBeenCalled(); // 不发必然失败的查询
140
+ });
141
+
142
+ it('匿名 + member.status 未配 loginUrl(深链解耦形态)→ 恒出无 URL 的 login 卡', async () => {
143
+ const service = stubService();
144
+ const listActivities = vi.fn(service.listActivities);
145
+ vi.mocked(resolveAlipayBumpInService).mockResolvedValue({ listActivities } as never);
146
+ const gate = async () => ({ outcome: 'unauthenticated' as const, loginUrl: '' });
147
+ const { ctx, execCtx } = ctxWith({ userId: 'u_anon', source: 'anonymous' }, gate);
148
+ const tools = createBumpInTools(() => ctx);
149
+ const result = (await tools.getBumpInActivity.execute!({} as never, execCtx('anonymous'))) as {
150
+ cards?: { cardType: string; data: Record<string, unknown> }[];
151
+ };
152
+ expect(result.cards?.[0]?.cardType).toBe('member-login-cta');
153
+ expect(result.cards?.[0]?.data).not.toHaveProperty('loginUrl');
154
+ expect(listActivities).not.toHaveBeenCalled();
155
+ });
156
+
157
+ it('GUEST(dev 身份,未入会)→ 放行,照常查询(登录 ≠ 入会,不得误伤)', async () => {
158
+ const gate = async () => ({ outcome: 'not_enrolled' as const, loginUrl: 'alipays://login' });
159
+ const service = stubService();
160
+ const listActivities = vi.fn(service.listActivities);
161
+ vi.mocked(resolveAlipayBumpInService).mockResolvedValue({ listActivities } as never);
162
+ const { ctx, execCtx } = ctxWith({ userId: 'u_dev', source: 'dev' }, gate);
163
+ const tools = createBumpInTools(() => ctx);
164
+ const result = (await tools.getBumpInActivity.execute!({} as never, execCtx('dev'))) as {
165
+ cards?: { cardType: string }[];
166
+ };
167
+ expect(result.cards?.[0]?.cardType).toBe('promotion-bumpin-activity');
168
+ expect(listActivities).toHaveBeenCalled();
169
+ });
170
+
171
+ it('handler:匿名 → login 卡直出(不触查询)', async () => {
172
+ const ctx = createServerContext();
173
+ Object.assign(ctx, { services: { resolve: (key: string) => (key === 'member.status' ? loginGate : undefined) } });
174
+ const service = stubService();
175
+ const listActivities = vi.fn(service.listActivities);
176
+ vi.mocked(resolveAlipayBumpInService).mockResolvedValue({ listActivities } as never);
177
+ const handler = createAlipayActivityHandler(ctx);
178
+ const result = await handler.handle('intent', { content: '碰出惊喜' }, ctx, {
179
+ identity: { userId: 'u_anon', source: 'anonymous' },
180
+ attributes: { mall: { miniAppId: 'app', mallId: 'mall-1' } },
181
+ });
182
+ expect(result.cards?.[0]?.cardType).toBe('member-login-cta');
183
+ expect(listActivities).not.toHaveBeenCalled();
184
+ expect(result.text).toBe('请先登录后再查看碰出惊喜活动');
185
+ });
186
+
187
+ it('inputSchema 已删 userId/openId(模型注入入参清理)', () => {
188
+ const tools = createBumpInTools(() => createServerContext());
189
+ const schema = (tools.getBumpInActivity as unknown as { inputSchema: { shape: Record<string, unknown> } }).inputSchema.shape;
190
+ expect(schema.userId).toBeUndefined();
191
+ expect(schema.openId).toBeUndefined();
192
+ });
193
+ });
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"]
8
+ }
package/tsup.config.ts ADDED
@@ -0,0 +1,36 @@
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 worker 以命令行式传参会撞 TS5074(incremental 需单文件 emit 或 tsBuildInfoFile);
16
+ // 声明产物一次性构建无需增量——仅 dts 关闭,typecheck 的增量缓存不受影响。
17
+ dts: { compilerOptions: { incremental: false } },
18
+ external: [
19
+ '@tbox.cn/app-sdk',
20
+ '@tbox.cn/app-contracts',
21
+ '@tbox.cn/app-contracts-mall',
22
+ 'react',
23
+ 'react-dom',
24
+ 'zod',
25
+ '@mastra/core',
26
+ 'express',
27
+ '@phosphor-icons/react',
28
+ 'alipay-sdk',
29
+ ],
30
+ loader: {
31
+ '.css': 'copy',
32
+ },
33
+ esbuildOptions(options) {
34
+ options.jsx = 'automatic';
35
+ },
36
+ });