@tbox.cn/app-provider-mock 0.4.0 → 0.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.
@@ -5,7 +5,7 @@
5
5
  * mock 实现经槽位轴产出(demo ref 厂商中立)。
6
6
  */
7
7
  import { beforeEach, describe, expect, it } from 'vitest';
8
- import { createIntegrationsRegistry, createAuthStrategyRegistry, createEnvironmentSecretProvider, createServerContext } from '@tbox.cn/app-sdk/server';
8
+ import { createIntegrationsRegistry, createAuthStrategyRegistry, createEnvironmentSecretProvider, createServerContext } from '@tbox.cn/app-agent-sdk-server';
9
9
  import { serverModule, enrollMockMember, logoutMockMember, __resetMockMemberState } from '../src/server/index';
10
10
  import { mallControlPlaneOf } from '@tbox.cn/app-contracts-mall/server';
11
11
  import type { IntegrationsConfig } from '@tbox.cn/app-contracts';
@@ -55,10 +55,11 @@ function requestContext(mallId = 'mall-demo'): RequestContext {
55
55
  };
56
56
  }
57
57
 
58
- function fixtureCtx(integrationsOverride?: IntegrationsConfig) {
58
+ function fixtureCtx(integrationsOverride?: IntegrationsConfig, ownerOf?: Record<string, string>) {
59
59
  const registry = createIntegrationsRegistry({
60
60
  integrations: integrationsOverride ?? integrations,
61
61
  catalog,
62
+ ...(ownerOf ? { ownerOf } : {}),
62
63
  authStrategies: createAuthStrategyRegistry(),
63
64
  secretProvider: createEnvironmentSecretProvider({ source: {}, production: false }),
64
65
  instanceIdOf: (scope) => scope.mallId ?? '',
@@ -238,86 +239,6 @@ describe('C5:scoped mock 换码器(入会闭环身份供给)', () => {
238
239
  });
239
240
  });
240
241
 
241
- describe('F2 端到端:config 级联(resolveService 全链——五层浅合并消费)', () => {
242
- it('槽级 config 流入:parking.query.config.feeCents=200 → 报价同源', async () => {
243
- const override: IntegrationsConfig = {
244
- ...integrations,
245
- services: {
246
- ...integrations.services,
247
- 'parking.query': { ...integrations.services['parking.query'], config: { feeCents: 200 } },
248
- },
249
- };
250
- const { ctx } = fixtureCtx(override);
251
- const parking = (await ctx.integrations!.resolveService({
252
- service: 'parking.query',
253
- scope: { mallId: 'mall-demo' },
254
- request: requestContext(),
255
- })) as { queryFee(q: unknown, input: { plateNo: string }): Promise<Array<{ totalCents: number; payableCents: number }>> };
256
- const quotes = await parking.queryFee({ scope: {} } as never, { plateNo: 'demo-plate' });
257
- expect(quotes[0]?.totalCents).toBe(200);
258
- expect(quotes[0]?.payableCents).toBe(200);
259
- });
260
-
261
- it('root config 级联:根 config.cardName → member 槽实例同源', async () => {
262
- const override: IntegrationsConfig = { ...integrations, config: { cardName: 'Root 卡' } };
263
- const { ctx } = fixtureCtx(override);
264
- const member = (await ctx.integrations!.resolveService({
265
- service: 'member.account',
266
- scope: { mallId: 'mall-demo' },
267
- request: requestContext(),
268
- })) as { queryPoints(u: string): Promise<{ membershipLabel: string }> };
269
- await expect(member.queryPoints('u1')).resolves.toMatchObject({ membershipLabel: 'Root 卡' });
270
- });
271
-
272
- it('浅合并键级覆盖:root 共享键 + slot 差异键并行生效(面板分层配置语义)', async () => {
273
- const override: IntegrationsConfig = {
274
- ...integrations,
275
- config: { parkName: 'RootP' },
276
- services: {
277
- ...integrations.services,
278
- 'parking.query': { ...integrations.services['parking.query'], config: { feeCents: 200 } },
279
- },
280
- };
281
- const { ctx } = fixtureCtx(override);
282
- const parking = (await ctx.integrations!.resolveService({
283
- service: 'parking.query',
284
- scope: { mallId: 'mall-demo' },
285
- request: requestContext(),
286
- })) as {
287
- queryFee(q: unknown, input: { plateNo: string }): Promise<Array<{ totalCents: number }>>;
288
- queryParkingInfo(q: unknown, kind: string): Promise<{ title: string }>;
289
- };
290
- const quotes = await parking.queryFee({ scope: {} } as never, { plateNo: 'demo-plate' });
291
- expect(quotes[0]?.totalCents).toBe(200); // slot 差异键
292
- const info = await parking.queryParkingInfo({ scope: {} } as never, 'chargeRules');
293
- expect(info.title).toBe('RootP'); // root 共享键
294
- });
295
-
296
- it('domain 层级联 + slot 胜 domain:域级键流入 + 槽级同名键覆盖(键级层序)', async () => {
297
- const override: IntegrationsConfig = {
298
- ...integrations,
299
- domains: { parking: { config: { parkName: 'DomainP', remainingSpaces: 99 } } },
300
- services: {
301
- ...integrations.services,
302
- 'parking.query': { ...integrations.services['parking.query'], config: { feeCents: 250, parkName: 'SlotP' } },
303
- },
304
- };
305
- const { ctx } = fixtureCtx(override);
306
- const parking = (await ctx.integrations!.resolveService({
307
- service: 'parking.query',
308
- scope: { mallId: 'mall-demo' },
309
- request: requestContext(),
310
- })) as {
311
- queryFee(q: unknown, input: { plateNo: string }): Promise<Array<{ totalCents: number }>>;
312
- queryParkingInfo(q: unknown, kind: string): Promise<{ title: string; entries: Array<{ label: string; value: string }> }>;
313
- };
314
- const quotes = await parking.queryFee({ scope: {} } as never, { plateNo: 'demo-plate' });
315
- expect(quotes[0]?.totalCents).toBe(250); // 槽级差异键
316
- const info = await parking.queryParkingInfo({ scope: {} } as never, 'chargeRules');
317
- expect(info.title).toBe('SlotP'); // slot 胜 domain(同名键)
318
- expect(info.entries).toContainEqual({ label: '剩余车位', value: '99' }); // 域级键流入(槽未覆盖)
319
- });
320
- });
321
242
 
322
243
  // ── 隐式默认单实例声明(零拓扑兜底——provider-mock declareProviderInstances) ──
323
244
 
@@ -44,13 +44,4 @@ describe('mockMallInfoFactory:请求形状守卫', () => {
44
44
  expect(MOCK_MALL_INFO_PROVIDER).toBe('mock');
45
45
  expect(MOCK_MALL_INFO_IMPL).toBe('mock-mall-info@1');
46
46
  });
47
-
48
- it('config 驱动:name 直出 / 空串回退动态别名 / 分式经纬度合法', async () => {
49
- const named = makePort({ name: '星河 Mock 小镇' });
50
- await expect(named.getMallInfo('1102588')).resolves.toMatchObject({ name: '星河 Mock 小镇' });
51
- const fallback = makePort({ name: '', latitude: 31.2304 });
52
- const info = await fallback.getMallInfo('1102588');
53
- expect(info?.name).toBe('示例商场(1102588)');
54
- expect((info as { latitude?: number })?.latitude).toBe(31.2304);
55
- });
56
47
  });
@@ -346,106 +346,3 @@ describe('provider-mock:登出态(logout 路由 + 换码降级 GUEST 形态
346
346
  await expect(member.getAccount(MOCK_SHELL_USER_ID)).resolves.toMatchObject({ state: 'active' });
347
347
  });
348
348
  });
349
-
350
- describe('provider-mock:config 驱动(fail-soft 快照)', () => {
351
- const enroll = (member: MockMemberServiceImpl, userId: string) =>
352
- member.enroll({ userId, identity: 'enrollment_submission', fieldValues: {}, acceptedConsentIds: [], idempotencyKey: `k-${userId}` });
353
-
354
- it('member 全字段:卡名/初值积分/等级/名称/深链/流水同源', async () => {
355
- const member = new MockMemberServiceImpl({}, { cardName: '黑金卡', initialPoints: 800, levelName: '金卡', memberName: '张三' });
356
- await enroll(member, 'u1');
357
- await expect(member.getCard('u1')).resolves.toMatchObject({ cardDisplay: '黑金卡', levelName: '金卡' });
358
- await expect(member.queryPoints('u1')).resolves.toMatchObject({ balance: 800, membershipLabel: '黑金卡' });
359
- await expect(member.getProfile('u1')).resolves.toMatchObject({ labels: [{ labelRef: 'demo:label:1', name: '张三' }] });
360
- const usage = await member.listPointUsage('u1', 1, 10);
361
- expect(usage.items[0].amount).toBe('+800');
362
- });
363
-
364
- it('member 非法值回退缺省:类型族/空串/NaN/分式整数(intKeys)', async () => {
365
- const member = new MockMemberServiceImpl({}, { initialPoints: 'x', cardName: '', enrollUrl: '', levelName: '' });
366
- await enroll(member, 'u1');
367
- await expect(member.queryPoints('u1')).resolves.toMatchObject({ balance: 300, membershipLabel: '示例会员卡' });
368
- const card = (await member.getCard('u1'))!;
369
- expect('levelName' in card).toBe(false);
370
- expect(member.enrollUrl).toMatch(/^alipays:\/\//);
371
- const nan = new MockMemberServiceImpl({}, { initialPoints: Number.NaN });
372
- await enroll(nan, 'u2');
373
- await expect(nan.queryPoints('u2')).resolves.toMatchObject({ balance: 300 });
374
- const fractional = new MockMemberServiceImpl({}, { initialPoints: 1500.5 });
375
- await enroll(fractional, 'u3');
376
- await expect(fractional.queryPoints('u3')).resolves.toMatchObject({ balance: 300 });
377
- });
378
-
379
- it('member 余额惰性读:入会不写种子 + 显式增减单源(queryPoints ≡ getBenefits)', async () => {
380
- const member = new MockMemberServiceImpl({}, { initialPoints: 500 });
381
- await expect(member.queryPoints('nobody')).resolves.toMatchObject({ balance: 0 });
382
- await enroll(member, 'u1');
383
- await expect(member.queryPoints('u1')).resolves.toMatchObject({ balance: 500 });
384
- await expect(member.getBenefits('u1')).resolves.toMatchObject({ availablePoints: 500 });
385
- await expect(member.deductPoints('u1', 100, 'd1')).resolves.toBe(true);
386
- await expect(member.deductPoints('u1', 1000, 'd2')).resolves.toBe(false);
387
- await expect(member.getBenefits('u1')).resolves.toMatchObject({ availablePoints: 400 });
388
- await expect(member.awardPoints('u1', 50)).resolves.toBe(true);
389
- await expect(member.refundPoints('u1', 25, 'r1')).resolves.toBe(true);
390
- await expect(member.queryPoints('u1')).resolves.toMatchObject({ balance: 475 });
391
- });
392
-
393
- it('parking 驱动:费用/权益开关/开票开关/信息/记录/寻车同源', async () => {
394
- const parking = new MockParkingServiceImpl('mall-demo', {
395
- feeCents: 200, parkName: 'P2 停车场', memberBenefitEnabled: false, invoiceEnabled: false, remainingSpaces: 56, vehicleSpaceNo: 'C-9',
396
- });
397
- const quote = (await parking.queryFee(parkCtx, { plateNo: 'demo-plate' }))[0];
398
- expect(quote).toMatchObject({ totalCents: 200, payableCents: 200 });
399
- expect(quote.feeItems[0]).toEqual({ name: '停车费(3 小时)', amountCents: 200 });
400
- const benefits = await parking.queryApplicableBenefits(parkCtx, 'demo-plate');
401
- expect(benefits).toHaveLength(1);
402
- expect(benefits[0].kind).toBe('points');
403
- await expect(parking.getInvoiceSettings()).resolves.toEqual({ parkingInvoiceEnabled: false });
404
- const info = await parking.queryParkingInfo(parkCtx, 'chargeRules');
405
- expect(info.title).toBe('P2 停车场');
406
- expect(info.entries).toContainEqual({ label: '剩余车位', value: '56' });
407
- expect(info.entries).toContainEqual({ label: '会员权益', value: '—' });
408
- await expect(parking.getOrderInfo(parkCtx, 'r')).resolves.toMatchObject({ payableFeeCents: 200 });
409
- const records = await parking.listPaymentRecords(parkCtx, 1, 10);
410
- expect(records.items[0]).toMatchObject({ parkName: 'P2 停车场', amountCents: 200 });
411
- expect((await parking.locateVehicle(parkCtx, 'demo-plate'))?.spaceNo).toBe('C-9');
412
- });
413
-
414
- it('promotion 驱动:券标题/面额/门槛 + 团购开关 + 资产/活动派生', async () => {
415
- const promotion = new MockPromotionServiceImpl({
416
- couponTitle: '满 200 减 50 元券', couponValueCents: 5000, couponThresholdCents: 20000, couponValidityDays: 7, grouponEnabled: false, activityTitle: '周年庆',
417
- });
418
- const page = await promotion.searchOffers(promoCtx, { keyword: '' });
419
- expect(page.items).toHaveLength(1);
420
- expect(page.items[0].title).toBe('满 200 减 50 元券');
421
- expect(page.items[0].facets[0]).toMatchObject({ value: 5000, thresholdCents: 20000 });
422
- const ents = await promotion.listEntitlements(promoCtx, {});
423
- expect(ents.items[0].title).toBe('满 200 减 50 元券');
424
- const acts = await promotion.listActivities();
425
- expect(acts.items[0].title).toBe('周年庆');
426
- await expect(promotion.getOfferDetail(promoCtx, { offerRef: 'demo:coupon:1001' })).resolves.toMatchObject({ title: '满 200 减 50 元券' });
427
- });
428
-
429
- it('shopping 驱动:追加门店进列表/类目/楼层目录', async () => {
430
- const impl = new MockShoppingServiceImpl(undefined, {
431
- extraShopName: '新店', extraShopFloor: '2 楼', extraShopCategory: '文创', extraShopUnit: '203', extraShopOpen: false,
432
- });
433
- const page = await impl.searchShops({ ctx: shopCtx, page: 1, pageSize: 20 });
434
- expect(page.total).toBe(13);
435
- const extra = page.items.find((s) => s.merchantId === 'demo-shop-1013');
436
- expect(extra).toMatchObject({ name: '新店', location: { floorName: '2 楼', unitName: '203' }, status: { code: 'disabled', label: '休息中' } });
437
- const cats = await impl.listCategories(shopCtx);
438
- expect(cats.find((c) => c.name === '文创')?.merchantCount).toBe(1);
439
- const dir = await impl.getDirectory(shopCtx);
440
- expect(dir?.buildings[0].floors.find((f) => f.floorName === '2 楼')?.merchantCount).toBe(3);
441
- expect((await impl.searchShops({ ctx: shopCtx, page: 1, pageSize: 20, floorCode: '2 楼' })).total).toBe(3);
442
- });
443
-
444
- it('shopping 消费点守卫:空白名不追加 + 未知楼层回退 3 楼', async () => {
445
- const blank = new MockShoppingServiceImpl(undefined, { extraShopName: ' ' });
446
- expect((await blank.searchShops({ ctx: shopCtx, page: 1, pageSize: 20 })).total).toBe(12);
447
- const badFloor = new MockShoppingServiceImpl(undefined, { extraShopName: 'X 店', extraShopFloor: '5 楼' });
448
- const page = await badFloor.searchShops({ ctx: shopCtx, page: 1, pageSize: 20, floorCode: '3 楼' });
449
- expect(page.items.some((s) => s.merchantId === 'demo-shop-1013')).toBe(true);
450
- });
451
- });
package/tsup.config.ts CHANGED
@@ -15,7 +15,8 @@ export default defineConfig({
15
15
  // 声明产物一次性构建无需增量——仅 dts 关闭,typecheck 的增量缓存不受影响。
16
16
  dts: { compilerOptions: { incremental: false } },
17
17
  external: [
18
- '@tbox.cn/app-sdk',
18
+ '@tbox.cn/app-agent-sdk-client',
19
+ '@tbox.cn/app-agent-sdk-server',
19
20
  '@tbox.cn/app-contracts',
20
21
  '@tbox.cn/app-contracts-mall',
21
22
  // mock-enroll-route 挂 express Router(devDep 不自动外部化——沿 module-member 先例显式声明,
@@ -1,11 +0,0 @@
1
- {
2
- "$schema": "https://json-schema.org/draft/2020-12/schema",
3
- "title": "Mock 商场基础信息实例配置",
4
- "type": "object",
5
- "properties": {
6
- "name": { "type": "string", "title": "商场名称", "description": "空串 = 动态别名「示例商场(mallId)」回退", "default": "" },
7
- "address": { "type": "string", "title": "商场地址", "default": "示例商场地址(demo)" },
8
- "latitude": { "type": "number", "minimum": -90, "maximum": 90, "title": "纬度(分式合法)", "default": 30 },
9
- "longitude": { "type": "number", "minimum": -180, "maximum": 180, "title": "经度(分式合法)", "default": 120 }
10
- }
11
- }
@@ -1,13 +0,0 @@
1
- {
2
- "$schema": "https://json-schema.org/draft/2020-12/schema",
3
- "title": "Mock 会员域实例配置",
4
- "type": "object",
5
- "properties": {
6
- "memberName": { "type": "string", "title": "会员名称", "description": "资料标签展示", "default": "示例会员" },
7
- "cardName": { "type": "string", "title": "会员卡名称", "description": "卡面与积分标签", "default": "示例会员卡" },
8
- "levelName": { "type": "string", "title": "等级名称", "description": "空串 = 不展示等级区", "default": "" },
9
- "initialPoints": { "type": "integer", "minimum": 0, "title": "初始积分", "description": "入会后余额;流水金额同源派生", "default": 300 },
10
- "enrollUrl": { "type": "string", "title": "入会落地页深链", "description": "alipays:// 或 H5", "default": "alipays://platformapi/startapp?appId=demo&page=v/index/index" },
11
- "loginUrl": { "type": "string", "title": "登录页深链", "description": "alipays:// 或 H5", "default": "alipays://platformapi/startapp?appId=demo&page=v/login/index" }
12
- }
13
- }
@@ -1,19 +0,0 @@
1
- {
2
- "$schema": "https://json-schema.org/draft/2020-12/schema",
3
- "title": "Mock 停车域实例配置",
4
- "type": "object",
5
- "properties": {
6
- "parkName": { "type": "string", "title": "停车场名称", "description": "信息卡标题 + 缴费记录", "default": "示例停车场" },
7
- "feeName": { "type": "string", "title": "费用项名称", "default": "停车费(3 小时)" },
8
- "feeCents": { "type": "integer", "minimum": 0, "title": "停车费(分)", "default": 1500 },
9
- "remainingSpaces": { "type": "integer", "minimum": 0, "title": "剩余车位", "default": 128 },
10
- "firstHourRate": { "type": "string", "title": "首小时费率文案", "default": "免费" },
11
- "memberBenefitEnabled": { "type": "boolean", "title": "会员折扣权益开关", "description": "关闭 = 权益列表少一项 + reprice 不变", "default": true },
12
- "memberBenefitDiscountCents": { "type": "integer", "minimum": 0, "title": "会员折扣权益预估减免(分)", "default": 75 },
13
- "pointsBenefitEnabled": { "type": "boolean", "title": "积分抵扣权益开关", "description": "关闭 = 权益列表少「积分抵 5 元」项(积分入口)", "default": true },
14
- "invoiceEnabled": { "type": "boolean", "title": "开票入口开关", "description": "关闭 = 缴费卡无开票按钮", "default": true },
15
- "vehicleFloor": { "type": "string", "title": "寻车楼层", "default": "B1" },
16
- "vehicleZone": { "type": "string", "title": "寻车区域", "default": "A 区" },
17
- "vehicleSpaceNo": { "type": "string", "title": "寻车车位号", "default": "A-128" }
18
- }
19
- }
@@ -1,13 +0,0 @@
1
- {
2
- "$schema": "https://json-schema.org/draft/2020-12/schema",
3
- "title": "Mock 营销域实例配置",
4
- "type": "object",
5
- "properties": {
6
- "couponTitle": { "type": "string", "title": "券标题", "description": "列表/详情/资产同源", "default": "满 100 减 20 元券" },
7
- "couponValueCents": { "type": "integer", "minimum": 0, "title": "券面额(分)", "default": 2000 },
8
- "couponThresholdCents": { "type": "integer", "minimum": 0, "title": "券门槛(分)", "default": 10000 },
9
- "couponValidityDays": { "type": "integer", "minimum": 1, "maximum": 365, "title": "券有效期(天)", "default": 30 },
10
- "grouponEnabled": { "type": "boolean", "title": "团购演示项开关", "description": "关闭 = 优惠列表仅券", "default": true },
11
- "activityTitle": { "type": "string", "title": "活动标题", "default": "示例商场周年庆" }
12
- }
13
- }
@@ -1,12 +0,0 @@
1
- {
2
- "$schema": "https://json-schema.org/draft/2020-12/schema",
3
- "title": "Mock 导购域实例配置",
4
- "type": "object",
5
- "properties": {
6
- "extraShopName": { "type": "string", "title": "追加门店名", "description": "空串 = 不追加", "default": "" },
7
- "extraShopCategory": { "type": "string", "title": "追加门店类目", "default": "餐饮" },
8
- "extraShopFloor": { "type": "string", "enum": ["B1", "1 楼", "2 楼", "3 楼", "4 楼"], "title": "追加门店楼层", "default": "3 楼" },
9
- "extraShopUnit": { "type": "string", "title": "追加门店铺位号", "default": "304" },
10
- "extraShopOpen": { "type": "boolean", "title": "追加门店营业状态", "default": true }
11
- }
12
- }
@@ -1,26 +0,0 @@
1
- /**
2
- * Mock 实例配置快照(fail-soft 单源):provider-mock 全部 config 消费的唯一读取面。
3
- * - 只透出 defaults 键(构造性防死字段);defaults 键 ≡ 被消费键;
4
- * - 非法回退缺省:类型族不符 / NaN / intKeys 键非整数 / 空串(统一「空串 = 缺省」语义);
5
- * - intKeys 显式列举而非按 default 值推断(JS 中 30.0 === 30,推断式必误拒分式经纬度);
6
- * - schema 是表单引导非门禁——守卫在消费侧(五层浅合并由平台侧完成,本层零合并逻辑)。
7
- * 双锁测试(tests/config-schema.test.ts)保证 schema.properties ≡ DEFAULTS 键集与 default 值。
8
- */
9
- export type CfgDefaults = Readonly<Record<string, string | number | boolean>>;
10
-
11
- export function resolveConfig<T extends CfgDefaults>(
12
- raw: unknown,
13
- defaults: T,
14
- intKeys: readonly string[] = [],
15
- ): T {
16
- const src = raw && typeof raw === 'object' ? (raw as Record<string, unknown>) : {};
17
- const out: Record<string, string | number | boolean> = {};
18
- for (const [key, fallback] of Object.entries(defaults)) {
19
- const value = src[key];
20
- const ok = typeof value === typeof fallback
21
- && (typeof value !== 'number' || (Number.isFinite(value) && (!intKeys.includes(key) || Number.isInteger(value))))
22
- && (typeof value !== 'string' || value !== '');
23
- out[key] = ok ? (value as string | number | boolean) : fallback;
24
- }
25
- return out as T;
26
- }
@@ -1,92 +0,0 @@
1
- /**
2
- * config schema 双锁(供给面 ↔ 消费面一致性):
3
- * ① 键集双向锁(schema.properties ≡ DEFAULTS——死字段/漏字段一次全拦)
4
- * ② default 漂移锁(schema 表单缺省 ≡ 实现缺省——面板不改动时的运行时真值)
5
- * ③ 整数对偶锁(schema type:'integer' ⟺ INT_KEYS——消费点整数守卫与表单引导同源)
6
- * ④ manifest 分发面锁(17 槽 configSchema 引用齐全 + 文件随包存在 + 槽→域文件映射)
7
- * ⑤ 楼层白名单同值锁(shopping enum ≡ SHOPPING_FLOORS——消费点守卫与引导同源)
8
- */
9
- import { describe, expect, it } from 'vitest';
10
- import { existsSync, readFileSync } from 'node:fs';
11
- import path from 'node:path';
12
- import { fileURLToPath } from 'node:url';
13
- import { MEMBER_CFG_DEFAULTS, MEMBER_CFG_INT_KEYS } from '../src/server/member';
14
- import { PARKING_CFG_DEFAULTS, PARKING_CFG_INT_KEYS } from '../src/server/parking';
15
- import { PROMOTION_CFG_DEFAULTS, PROMOTION_CFG_INT_KEYS } from '../src/server/promotion';
16
- import { SHOPPING_CFG_DEFAULTS, SHOPPING_CFG_INT_KEYS, SHOPPING_FLOORS } from '../src/server/shopping';
17
- import { MALL_INFO_CFG_DEFAULTS, MALL_INFO_CFG_INT_KEYS } from '../src/server/mall-info';
18
-
19
- const pkgRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
20
-
21
- interface SchemaProperty { type?: string; default?: unknown; enum?: readonly string[] }
22
- interface SchemaFile { properties: Record<string, SchemaProperty> }
23
-
24
- interface DomainCase {
25
- name: string;
26
- file: string;
27
- defaults: Readonly<Record<string, string | number | boolean>>;
28
- intKeys: readonly string[];
29
- }
30
-
31
- const DOMAINS: readonly DomainCase[] = [
32
- { name: 'member', file: 'member.config.json', defaults: MEMBER_CFG_DEFAULTS, intKeys: MEMBER_CFG_INT_KEYS },
33
- { name: 'parking', file: 'parking.config.json', defaults: PARKING_CFG_DEFAULTS, intKeys: PARKING_CFG_INT_KEYS },
34
- { name: 'promotion', file: 'promotion.config.json', defaults: PROMOTION_CFG_DEFAULTS, intKeys: PROMOTION_CFG_INT_KEYS },
35
- { name: 'shopping', file: 'shopping.config.json', defaults: SHOPPING_CFG_DEFAULTS, intKeys: SHOPPING_CFG_INT_KEYS },
36
- { name: 'mall-info', file: 'mall-info.config.json', defaults: MALL_INFO_CFG_DEFAULTS, intKeys: MALL_INFO_CFG_INT_KEYS },
37
- ];
38
-
39
- const readSchema = (file: string): SchemaFile =>
40
- JSON.parse(readFileSync(path.join(pkgRoot, 'schemas', file), 'utf8')) as SchemaFile;
41
-
42
- describe('provider-mock:config schema 双锁(供给面 ≡ 消费面)', () => {
43
- it('① 键集双向锁:schema.properties ≡ DEFAULTS 键集', () => {
44
- for (const d of DOMAINS) {
45
- const schema = readSchema(d.file);
46
- expect(Object.keys(schema.properties).sort(), `${d.name} 键集`).toEqual(Object.keys(d.defaults).sort());
47
- }
48
- });
49
-
50
- it('② default 漂移锁:schema 缺省 ≡ 实现缺省', () => {
51
- for (const d of DOMAINS) {
52
- const schema = readSchema(d.file);
53
- for (const [key, value] of Object.entries(d.defaults)) {
54
- expect(schema.properties[key]?.default, `${d.name}.${key} default 漂移`).toEqual(value);
55
- }
56
- }
57
- });
58
-
59
- it('③ 整数对偶锁:schema type=integer ⟺ INT_KEYS(分式字段不得入 intKeys)', () => {
60
- for (const d of DOMAINS) {
61
- const schema = readSchema(d.file);
62
- for (const [key, prop] of Object.entries(schema.properties)) {
63
- expect(prop.type === 'integer', `${d.name}.${key} 整数对偶`).toBe(d.intKeys.includes(key));
64
- }
65
- }
66
- });
67
-
68
- it('④ manifest 分发面锁:17 槽引用齐全 + 槽→域映射 + 文件随包', () => {
69
- const manifest = JSON.parse(readFileSync(path.join(pkgRoot, 'tbox.module.json'), 'utf8')) as {
70
- contributes: { providers: { slots: Array<{ service: string; configSchema?: string }> } };
71
- };
72
- const slots = manifest.contributes.providers.slots;
73
- expect(slots).toHaveLength(17);
74
- const fileOfPrefix: Record<string, string> = {
75
- member: 'member.config.json',
76
- parking: 'parking.config.json',
77
- promotion: 'promotion.config.json',
78
- 'shopping-guide': 'shopping.config.json',
79
- mall: 'mall-info.config.json',
80
- };
81
- for (const slot of slots) {
82
- const prefix = slot.service.slice(0, slot.service.indexOf('.'));
83
- expect(slot.configSchema, `${slot.service} configSchema 缺失`).toBe(`schemas/${fileOfPrefix[prefix]}`);
84
- expect(existsSync(path.join(pkgRoot, slot.configSchema!)), `${slot.service} schema 文件不存在`).toBe(true);
85
- }
86
- });
87
-
88
- it('⑤ 楼层 enum ≡ SHOPPING_FLOORS(消费点守卫与表单引导同源)', () => {
89
- const schema = readSchema('shopping.config.json');
90
- expect(schema.properties.extraShopFloor?.enum).toEqual([...SHOPPING_FLOORS]);
91
- });
92
- });